Dependency injection in angular

Dependency injection in angular

Dependency Injection, or DI, is a design pattern and mechanism for creating and delivering some parts of an application to other parts of an application that require them.

In the element dependency injection angular start terversing from that element (component/directive)

to above its parent elements for checking that if its parent has that same provider or not

At the beginning we go up through element inject hierarchy and encounter the root element injector

And till the root element injector if in hierarchy if any element has that injector then it returns that instance. And if till root element there is no service injected which this element is trying to find then root element says hey man sorry but i don't have what you are looking for.

After that this element goes up through module inject hierarchy and try to find this dependency provider is in any module or not. up till that root -->platform module --> after that if this service is not provided any where then it shows us error from

Null injector that this service has no provider

Note- if any service is injected in any directive then angular will start from this directive to find dependency provider and then first it will goes up to host elements which means its parent directive and then in components hierarchy and then modules.

Resolution modifiers are special annotations which allows you to slightly change the logic of how angular resolves any dependency in the injector tree

There are 4 resolution modifiers in angular

@Optional() @Self() @KeepSelf() @Host()

@Optional()

With this resolution modifier if we inject any service then it will not throws any error if angular does not found providation for this injected service. instead of error it will just get null

@Self()

With this resolution modifier if we inject any service then it will throws error of not found service even if this service is provided in the root.

It means with @self angular only tries to resolve this service with its own element

Example - if any component/directive/module have any injected service and this service is not provided

In this element itself then it will throws error of not found or output null if we uave used @Optional()also even if this provided in the root or up in the hierarchy.it will not goes up in the hierarchy also.