in angular 1 used factories services store shared state accessible many components. looks in angular 2 services injected @injectable() created each time, losing shared state.
i 'register' service @ root module's providers
meta key, still transient instance.
what have:
injectable() export class artistservice { constructor(private http:http) { // firing on each injection console.log("artistservice ctor"); } }
to call in component then:
@component({ selector: 'artist-display', templateurl: './artistdisplay.html', }) export class artistdisplay { constructor(private artistservice: artistservice) { // instance fine transient } }
and definition of module:
@ngmodule({ declarations: [...], imports: [browsermodule, formsmodule, httpmodule, routermodule.forroot(rootrouterconfig)], providers : [ artistservice, // make sure use hash urls rather html 5 routing { provide: locationstrategy, useclass: hashlocationstrategy }, ], bootstrap: [appcomponent] })
i suspect there maybe other way 'register' artistservice
stays loaded static instance? possible via di or necessary create static instance method manually?
update:
turns out above code does work. looking in wrong place along logic error caused data not cache correctly.
the above code works , assigning service in providers
section of top level appmodule key making parent reference stay loaded duration of appcomponent. stays loaded lifetime of app providing singleton instance.
to transient instance can declare providers
meta tag , service name on actual component create service whenever component loaded/re-loaded.
what have shown correct way. creates single instance shared among components.
https://plnkr.co/edit/fbca39yc4zpoy6y8ozql?p=preview reference purpose.
import { ngmodule } '@angular/core'; import { browsermodule } '@angular/platform-browser'; import { appcomponent } './app.component'; import {service} './service'; @ngmodule({ imports: [ browsermodule ], declarations: [ appcomponent], providers:[service], bootstrap: [ appcomponent ] }) export class appmodule { }
Comments
Post a Comment