In Angular 1, I often used service factories to store the general state that is available for many components. It seems that in Angular 2, all services that are introduced as @Injectable () are created every time, thereby losing their general state.
I 'register' the service in the root module of the meta key providers , but still I get a temporary instance.
What I have:
Injectable() export class ArtistService { constructor(private http:Http) {
to call it in the component, then:
@Component({ selector: 'artist-display', templateUrl: './artistDisplay.html', }) export class ArtistDisplay { constructor(private artistService: ArtistService) {
And the definition of the module:
@NgModule({ declarations: [...], imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(rootRouterConfig)], providers : [ ArtistService, // make sure you use this for Hash Urls rather than HTML 5 routing { provide: LocationStrategy, useClass: HashLocationStrategy }, ], bootstrap: [AppComponent] })
I suspect there might be some other way to βregister" the ArtistService so that it ArtistService loaded as a static instance? Is this possible using DI or is it necessary to create a static instance method manually?
Update:
It turns out that the code above works . I was looking for the wrong place and a logical error that led to incorrect data caching.
The code above works and assigns the service in the top-level providers section of the top-level AppModule - this is the key to keep the parent link loaded for the duration of the AppComponent. which actually stays loaded for the lifetime of the application, providing an instance of Singleton .
To get a transient instance, you can declare the meta tag providers and the service name on the actual component , which will then create the service when the component is loaded / reloaded.