2016-03-17 30 views
20

Từ Angular2 access global service without including it in every constructor Tôi đã chộp lấy mã và một chút thay đổi nó thành:Angular2 không cung cấp cho lỗi dịch vụ

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

} 

Tuy nhiên, khi tôi cố gắng để chạy mã này, tôi nhận được một lỗi trong giao diện điều khiển:

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

Tôi đã tạo một Plunkr với mã số tại https://plnkr.co/edit/We2k9PDsYMVQWguMhhGl

Có ai biết nguyên nhân gây ra lỗi này không?

Trả lời

27

Bạn cũng cần xác định ApiService trong thuộc tính providers.

@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(); 
    } 
} 

Đó là vì kim phun được dựa vào thành phần. Nếu bạn muốn có thêm chi tiết về làm thế nào để tiêm một dịch vụ vào một dịch vụ, bạn có thể có một cái nhìn tại câu hỏi này:

Các vấn đề liên quan