@Self, @SkipSelf and @Optional are Angular Decorators that configure how the DI Framework should resolve the dependencies. These decorators are called Resolution Modifiers because they modify the behavior of injectors. In this page, we will learn @Self, @SkipSelf, & @Optional.
How Angular DI Framework Resolves Dependencies
When a component asks for Dependency, the DI Framework resolves it in two phases.
In the first phase, it starts to look for the Dependency in the current component’s ElementInjector. If it does not provide the Dependency, it will look in the Parent Components ElementInjector. The Request bubbles up until it finds an injector that provides the service or reaches the root ElementInjector.
If ElementInjector does not satisfy the request, Angular looks for the Dependency in the ModuleInjector hierarchy. If Angular still doesn’t find the provider, it throws an error.
We have created an example project in Angular to explain the @Self, @SkipSelf, & @Optional.
The Code contains a RandomService, which generates a Random Number when initialized. The Angular Service is added to the Providers array of the AppModule. We can inject this service anywhere in our Application.
The project contains three Angular Components (AppComponent, ChildComponent & GrandChildComponent) all inject the RandomService and displays the Random Number from the Service.
We also have testDirective, which we include in the template of GrandChildComponent. It also displays the Random Number from the Service.
Ensure that the Providers array is empty in all components & directives. Run the App. Angular creates only one instance of the RandomService. That is why all the components and directives show the same number.
@Self: The @Self decorator instructs Angular to look for the dependency only in the local injector. The local injector is the injector that is part of the current component or directive.
@Optional: Optional marks the dependency as Optional. If the dependency is not found, then it returns null instead of throwing an error
In the GrandChildComponent remove the RandomService from the Providers Array and add the @Self decorator. You will instantly receive the error “No provider for RandomService found in NodeInjector“.
Add the @Optional decorator along with the @Self. Now, the dependency injection will return null instead of an error.
Also, remember to add the ? in randomService?, else you will get the “Cannot read property ‘RandomNo’ of null” error.
As you can see in the image, GrandChildComponent does not receive any values, while testDirective picks up the RandomService provided by the AppModule
0 comments:
Post a Comment