[英]Inject custom service in another service in Angular 2
我想将服务注入另一个服务。 注入标准的角度服务(Http等)没有任何问题,但是当我尝试注入自己的服务时,我得到了很多帮助。
例:
我的服务:
import {Injectable, Inject} from 'angular2/core';
import {AnotherService} from '../../services/another.service';
@Injectable()
export class MyService {
constructor(Inject(AnotherService) private anotherService: AnotherService) {
console.log(this.anotherService.get());
}
}
AnotherService:
import {Injectable} from 'angular2/core';
@Injectable()
export class AnotherService {
constructor() { }
get() { return 'hello'); }
}
当我尝试使用MyService时,出现EXCEPTION: No provider for AnotherService!
我试过使用constructor(private anotherService: AnotherService)
,仍然抛出异常。
谢谢!
您应该阅读Angular 2文档。 您的确切问题在以下角度文档中得到了解释: https : //angular.io/docs/ts/latest/guide/dependency-injection.html#when-the-service-needs-a-service
您必须将服务添加到providers数组。 无需执行此操作即可使用Http的唯一原因是因为Ionic为您将其放在了provider数组中。 如果使用的是香草Angular 2,则仍必须将HTTP_PROVIDERS添加到providers数组。
附带说明一下,您不需要在构造函数中使用Inject,只需执行以下操作:
constructor(private anotherService: AnotherService) {
console.log(this.anotherService.get());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.