Search code examples
angularangular2-services

Angular 2 Services Dependency Injection Issue


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.


Solution

  • 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.