Injecting Services into Other Services in Angular 2 (Beta)
Injecting services into components is straightforward using the @Component decorator. However, injecting services outside of components poses a challenge.
Problem Statement
In Angular 2, we want to avoid manually instantiating services within other services, as seen in the following code snippet:
export class MyFirstSvc { } export class MySecondSvc { constructor() { this.helpfulService = new MyFirstSvc(); } } export class MyThirdSvc { constructor() { this.helpfulService = new MyFirstSvc(); } }
Solution
The solution involves using the @Injectable decorator on the services that we wish to inject. This decorator prepares the constructor parameters of the service for dependency injection.
Injector Hierarchy
To understand how injection works, it's essential to grasp the concept of the injector hierarchy:
When injecting a service into a component or another service, Angular2 searches for the provider in the following order:
Provider Sharing
The injector hierarchy allows for controlled sharing of service instances:
Example
@Injectable() export class Service1 { constructor(service2:Service2) { this.service2 = service2; } getData() { return this.service2.getData(); } }
@Injectable() export class Service2 { getData() { return [{ message: 'message1' }, { message: 'message2' }]; } }
In this example:
Resources
The above is the detailed content of How can I inject services into other services in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!