HI WELCOME TO SIRIS

Angular Injector

Leave a Comment

how it is implemented in Angular. There are 2 simple steps to use dependency injection in Angular. For example, if you have a component that depends on a service and needs an instance of it,


Step 1 : First register the service with the angular injector
Step 2 : Specify a dependency using the constructor of your component class.


With these 2 steps in place, the angular injector will automatically inject an instance of the the service into the component's constructor when an instance of the component is created.

Angular 1 has only one global injector but in Angular 2 we have one injector at the application root level and hierarchical injectors that parallel an application's component tree. This means in Angular 2, we have one root injector plus an injector at every component level as you can see from the diagram below.

angular 2 injector example

If a service is registered with the root injector then that service is available for all components in our entire application including the components in lazy loaded modules. We will discuss lazy loaded modules in a later video in this series.

If a service is registered with the injector at the Application Root component level, then that service is available for all the components in the application except the components in lazy loaded modules.

If a service is registered with a specific component injector, then that service is available for that component and any of it's children. For example, if we register a service with Component X injector, then that service is available for Components X, Y & Z but not for Component A. Similarly if a we register a service with Component A injector, then that service is available only for Component A but not for Components X, Y & Z.

We can register a service with the angular injector using the providers property of @Component decorator or @NgModule decorator.

To register a service with the root injector use providers property of @ngModule decorator of root module (app.module.ts) or any feature module

To register a service with the injector at a component levet use providers property of @Component decorator

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.