从
Angular2 access global service without including it in every constructor我已经抓住代码,稍微修改为:
@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") } }
NoProviderError {message: “No provider for ApiService! (App ->
MediaService -> ApiService)”,stack: “Error: DI Exception↵
我已经在https://plnkr.co/edit/We2k9PDsYMVQWguMhhGl创建了一个Plunkr的代码
有谁知道是什么原因导致这个错误?
您还需要在providers属性中定义ApiService.
原文链接:https://www.f2er.com/angularjs/140592.html@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(); } }
这是因为注射器依赖组件.如果您想了解有关如何将服务注入服务的更多详细信息,可以看看这个问题:
> What’s the best way to inject one service into another in angular 2 (Beta)?