[英]Angular2 no provider for service error
From Angular2 access global service without including it in every constructor I have grabbed the code and slightly modified it into: 从Angular2访问全局服务,而不是在每个构造函数中都包含它我已经抓住了代码并将其稍微修改为:
@Injectable()
export class ApiService {
constructor(public http: Http) {}
get(url: string) {
return http.get(url);
}
}
@Injectable()
export abstract class BaseService {
constructor(protected serv: ApiService) {}
}
@Injectable()
export class MediaService extends BaseService {
// Why do we need this?
constructor(s: ApiService) {
super(s)
}
makeCall() {
this.serv.get("http://www.example.com/get_data")
}
}
However, when I try to run this code I get an error in the console: 但是,当我尝试运行此代码时,我在控制台中收到错误:
NoProviderError {message: "No provider for ApiService! (App -> MediaService -> ApiService)", stack: "Error: DI Exception↵
NoProviderError {message:“没有ApiService的提供者!(App - > MediaService - > ApiService)”,堆栈:“错误:DI异常↵
I have created a Plunkr with the code at https://plnkr.co/edit/We2k9PDsYMVQWguMhhGl 我创建了一个Plunkr,其代码位于https://plnkr.co/edit/We2k9PDsYMVQWguMhhGl
Does anyone know what causes this error? 有谁知道导致此错误的原因是什么?
You need to also define ApiService
in the providers
attribute. 您还需要在
providers
属性中定义ApiService
。
@Component({
selector: 'my-app',
providers: [MediaService, ApiService], // <-----
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
directives: []
})
export class App {
constructor(mediaService: MediaService) {
this.name = 'Angular2'
console.log('start');
mediaService.makeCall();
}
}
It's because injectors are relied on components. 这是因为注射器依赖于组件。 If you want to have more details about how to inject a service into a service, you could have a look at this question:
如果您想了解有关如何将服务注入服务的更多详细信息,您可以查看以下问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.