Javascript 在Angular 2中的另一个服务中注入自定义服务
我想将服务注入到另一个服务中。我在注入标准angular服务(Http等)时没有任何问题,但是当我尝试注入我自己的服务时,我得到了一个exeption 例如: 我的服务:Javascript 在Angular 2中的另一个服务中注入自定义服务,javascript,dependency-injection,angular,ionic2,Javascript,Dependency Injection,Angular,Ionic2,我想将服务注入到另一个服务中。我在注入标准angular服务(Http等)时没有任何问题,但是当我尝试注入我自己的服务时,我得到了一个exeption 例如: 我的服务: import {Injectable, Inject} from 'angular2/core'; import {AnotherService} from '../../services/another.service'; @Injectable() export class MyService { construct
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时,我得到了异常:没有其他服务的提供者代码>
我尝试使用构造函数(private-anotherService:anotherService)
,但仍然抛出异常
谢谢 您应该阅读Angular 2文档。您的确切问题将在以下文档中解释:
您必须将服务添加到提供商阵列。您可以使用Http而不这样做的唯一原因是,Ionic为您将其放在providers数组中。如果您使用的是vanilla Angular 2,那么仍然需要将HTTP_提供程序添加到提供程序数组中
作为补充说明,您不需要在构造函数中使用该注入,只需执行以下操作:
constructor(private anotherService: AnotherService) {
console.log(this.anotherService.get());
}
非常感谢你!现在可以了!我刚刚在组件的提供者中指定了另一个服务。我应该更仔细地阅读这些文件。