Angular2没有提供服务错误

Bas*_*ijk 20 typescript angular

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")
  }

}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行此代码时,我在控制台中收到错误:

NoProviderError {message:"没有ApiService的提供者!(App - > MediaService - > ApiService)",堆栈:"错误:DI异常↵

我创建了一个Plunkr,其代码位于https://plnkr.co/edit/We2k9PDsYMVQWguMhhGl

有谁知道导致此错误的原因是什么?

Thi*_*ier 28

您还需要ApiServiceproviders属性中定义.

@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();
  }
}
Run Code Online (Sandbox Code Playgroud)

这是因为注射器依赖于组件.如果您想了解有关如何将服务注入服务的更多详细信息,您可以查看以下问题: