Dependency Injection in Angular 2: Injecting Services Outside of Components
In Angular 2, injecting services into components is straightforward using the @Component decorator. However, there are scenarios where you may need to inject services outside of components. This article explores how to accomplish this using dependency injection (DI).
Injectable Services
To enable DI for a service, it must be decorated with the @Injectable decorator. This decorator marks the class as injectable, allowing its parameters to be injected. Note that the name "Injectable" is slightly misleading, as it does not make the class injectable but rather makes it injectable in the sense that its parameters can be injected.
Dependency Injection Mechanism
Angular 2 uses a hierarchical system of injectors, with each level corresponding to a particular component or set of components. When the DI system encounters a dependency, it first looks in the current injector. If the dependency is not found, it moves up the injector hierarchy until it finds a provider for the dependency.
Injecting Services Across Injectors
To inject a service into another service, simply define the dependency in the constructor of the dependent service and add the @Injectable decorator to the dependent service.
For example:
@Injectable() export class MyFirstSvc { // ... } @Injectable() export class MySecondSvc { constructor(private myFirstSvc: MyFirstSvc) { // ... } }
In this example, MySecondSvc depends on MyFirstSvc and can be injected into any injector where MyFirstSvc is available.
Defining Providers
To specify the provider for a service, use the providers array in the @Component or NgModule decorator. For example, if you want to define MyFirstSvc as a provider in the application injector, you can do so as follows:
@Component({ // ... providers: [MyFirstSvc] }) export class AppComponent { // ... }
Conclusion
By understanding the hierarchical nature of injectors and the @Injectable decorator, you can effectively inject services outside of components in Angular 2. This allows you to create modular and reusable services that can be easily injected and shared across your application.
The above is the detailed content of How to Inject Services Outside of Components in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!