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
以上是如何將服務注入 Angular 2 中的其他服務?的詳細內容。更多資訊請關注PHP中文網其他相關文章!