我想将服务注入另一个服务.我注入标准角度服务(Http等)没有任何问题,但是当我尝试注入自己的服务时,我得到了一个例外.
例:
为MyService:
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:没有为AnotherService提供服务器!
我试过使用构造函数(private anotherService:AnotherService),仍然抛出异常.
谢谢!
解决方法:
您应该阅读Angular 2文档.您在这里的角度文档中解释了您的确切问题:https://angular.io/docs/ts/latest/guide/dependency-injection.html#when-the-service-needs-a-service
您必须将服务添加到提供程序数组.您可以在不执行此操作的情况下使用Http的唯一原因是因为Ionic将它放在提供程序数组上.如果你使用的是vanilla Angular 2,你仍然需要将HTTP_PROVIDERS添加到providers数组中.
作为旁注,您不需要在构造函数中使用Inject,您可以这样做:
constructor(private anotherService: AnotherService) {
console.log(this.anotherService.get());
}
原文地址:https://codeday.me/bug/20190519/1135406.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。