Home > Article > Web Front-end > How Does Dependency Injection Work Beyond Angular 2 Components?
Injecting Services in Angular 2 (Beta)
In Angular 2, injecting a service into a component is straightforward, but how can we utilize dependency injection (DI) to transfer services beyond components?
Injecting Services Outside of Components
To achieve this, we annotate the desired services with the @Injectable decorator. This decorator signifies that the parameters within the constructor of the annotated class should receive injections.
Understanding the Injection Mechanism
The DI mechanism in Angular 2 operates on a tree of injectors linked in a hierarchical structure. These injectors map onto the component tree, but there are no specific injectors for services.
When a service is annotated with @Injectable, Angular attempts to create or retrieve an instance for that service type within the injector for the current execution chain.
Example: Service Injection Chain
Consider the following sample application:
Each service and component is annotated with @Injectable.
Injector Hierarchy and Service Injection
In this application, we have three injectors:
When injecting Service1 into ChildComponent, Angular searches for a Service1 provider first in the ChildComponent injector, then in the AppComponent injector, and finally in the application injector.
Similarly, when injecting Service2 into Service1, the same search process occurs.
Provider Scope and Injector Hierarchy
This search process determines where to instantiate and share service instances. Providers can be specified at different levels:
Conclusion
By leveraging the @Injectable decorator and understanding the DI mechanism in Angular 2, we can effectively inject services between components and services, allowing us to organize and share dependencies as needed.
The above is the detailed content of How Does Dependency Injection Work Beyond Angular 2 Components?. For more information, please follow other related articles on the PHP Chinese website!