2016-03-17 72 views
20

Angular2 access global service without including it in every constructor我已经抓住了代码,并略作修改成: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") 
    } 

} 

然而,当我尝试运行此代码,我在控制台中的错误:

NoProviderError {message: "No provider for ApiService! (App -> MediaService -> ApiService)", stack: "Error: DI Exception↵

我在https://plnkr.co/edit/We2k9PDsYMVQWguMhhGl

创建Plunkr与代码

有谁知道是什么原因导致这个错误?

回答

27

您还需要在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(); 
    } 
} 

这是因为注射器依赖于组件。如果你想有关于如何注入一个服务为一体的服务更多的细节,你可以看看这个问题:

相关问题