Overwrite a Service in a Component Subtree in Angular

Share this video with your friends

Send Tweet

Angular's hierarchical dependency allows us to overwrite a global service with a different class implementation for just a given sub-tree of the entire component tree of your application.

In this lesson we will take a look how this works, by registering the service on the component's child injector.

Enoh Barbu
Enoh Barbu
~ 7 years ago

why do I need to override PeopleService with WomanService into providers section? Couldn't I just provide the WomanService directly into the constructor?

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 7 years ago

Hey. Sure. You could directly use the WomenService in the WomenComponent of my example. The point here though is that in this way you can overwrite/specialize an entire subtree of your component tree. As I explain in the example towards the end, even if we place the <app-person> inside the template of the WomenComponent, it will also get the instance of our WomanService (though in its constructor it fetches a PersonService).

So without even changing the implementation of the component, we can still influence how it fetches data via this mechanism.

Enoh Barbu
Enoh Barbu
~ 7 years ago

Ohh, now I see, the override will affect the current components and it's children that use the PeopleService. I've replayed the video and I saw that you did within WomanComponent. Thanks!

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 7 years ago

👌

Sreekanth
Sreekanth
~ 6 years ago

Hi guess, in this case (useExisting will also work in addition to PersonService)

{ provide : PeopleService, useExisting: WomanService } will work, since WomanService is available from the parent app-module injector.