在 Angular 2 中的另一个服务中注入自定义服务
Inject custom service in another service in Angular 2
我想将服务注入到另一个服务中。我在注入标准 angular 服务(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());
}
}
另一个服务:
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 文档。您的确切问题在此处的 angular 文档中进行了解释:https://angular.io/docs/ts/latest/guide/dependency-injection.html#when-the-service-needs-a-service
您必须将您的服务添加到提供程序数组中。您可以在不执行此操作的情况下使用 Http 的唯一原因是因为 Ionic 为您将其放在 providers 数组中。如果您使用的是 vanilla Angular 2,您仍然需要将 HTTP_PROVIDERS 添加到 providers 数组。
附带说明一下,您不需要在构造函数中注入,您可以这样做:
constructor(private anotherService: AnotherService) {
console.log(this.anotherService.get());
}
我想将服务注入到另一个服务中。我在注入标准 angular 服务(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());
}
}
另一个服务:
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 文档。您的确切问题在此处的 angular 文档中进行了解释:https://angular.io/docs/ts/latest/guide/dependency-injection.html#when-the-service-needs-a-service
您必须将您的服务添加到提供程序数组中。您可以在不执行此操作的情况下使用 Http 的唯一原因是因为 Ionic 为您将其放在 providers 数组中。如果您使用的是 vanilla Angular 2,您仍然需要将 HTTP_PROVIDERS 添加到 providers 数组。
附带说明一下,您不需要在构造函数中注入,您可以这样做:
constructor(private anotherService: AnotherService) {
console.log(this.anotherService.get());
}