Reputation: 10386
In my app I have a Module with two components, ListComponent and DetailsComponent and a service MyModuleService.
When users visits the ListComponet, I fetch the list from the server and add it to the List property of the service (which I then use as a cache).
When User clicks any item in the list, its taken to the Details page of that item.
In details component I have navigation with Next and Previous links, I use the List property of the service to decide about the next and previous item.
If a user go back to the list page, the list is rendered from the cache i.e. from the List property of the service.
My List component also have a search form which allow users to specify search criteria and retrieve items from server matching that criteria.
The issue is, if I navigate to any other route which doesn't have any reference to above mentioned MyModule and then come back to the list page, it doesn't refresh the MyModuleService which means that it didn't destroy the Service instance.
Probably because the MyModuleService is added to global dependency injection context.
Can anyone please guide, how do I limit the scope of a service to a module only? so that when I navigate away to another route it destroys the MyModuleService instance.
Upvotes: 1
Views: 647
Reputation: 56986
To provide different instances of the service to different modules use the providers array.
Module1:
providers: [MyService]
Module2:
providers: [MyService]
Now these two modules are using different instances of the same service.
You can declare a provider at a component level if you want. That means that that component and any sub components will have instance to that individual instance of the service.
If you want the whole app to use just once instance of a service then provide it in the providers array at the top level module.
Upvotes: 1
Reputation: 8043
Probably because the MyModuleService is added to global dependency injection context.
Yes, and this is by design.
The way to restrict the scope to the module is by using a "top component" in the module (as said in the given documentation link), then declaring the service in the providers
array of the @Component
decorator:
@Component({
selector: 'my-top-component',
providers: [ MyModuleService ]
})
export class MyTopComponent { }
This way, MyModuleService
scope will be restricted to MyTopComponent
and its children. But since you'll have two nested components (ListComponent
and DetailsComponent
) inside MyTopComponent
, you'll have to deal with child routes too.
Upvotes: 2