我爲接口創建了2個實現,併爲這兩個不同組件提供了這些實現。我得到這個錯誤錯誤:無法解析ChildComponent的所有參數:(?)。Angular 2 - DI不工作
我在哪裏做錯了?
interface MyInterface {
log(msg: string): void
}
class DebugService implements MyInterface {
public log(msg:string) {
console.debug(msg);
}
}
class ErrorService implements MyInterface {
public log(msg: string) {
console.error(msg);
}
}
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<div (click)="log()">Root Component</div><my-child></my-child><my-child></my-child>' //app/app.component.html
, providers: [DebugService]
})
export class AppComponent {
private dummy: MyInterface;
constructor(d: MyInterface) {
this.dummy = d;
}
log() {
this.dummy.log("Root");
}
}
@Component({
selector: 'my-child',
template: `<h4 (click)="log()"> Hello Child</h4>`,
providers: [ErrorService]
})
export class ChildComponent {
private dummy: MyInterface;
constructor(d: MyInterface) {
this.dummy = d;
}
log() {
this.dummy.log("Child");
}
}
這是不正確的。 @Injectable()*是DI工作所必需的,正如它在[@angular documentation]中所述(https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#injectable) :_「@ Injectable()將一個類標記爲可用於實例化的注入器。一般而言,當試圖實例化未標記爲@Injectable()的類時,注入器將報告錯誤。」_ – nickspoon
@nickspoon - an從您提供的文檔鏈接中抽象出來,「我們建議將Injectable()添加到每個服務類,即使那些沒有依賴關係,因此在技術上也不需要它。」僅當服務依賴於其他服務時才需要注入裝飾器。 Angular文檔清楚地表明這不是必需的,但即使服務類沒有依賴關係,它也是用Injectable()來裝飾服務類的「約定」。 – user1176058
對不起,你是對的,我剛剛測試過,沒有依賴關係的服務可以在沒有'@Injectable()'的情況下注入。所以你的問題的答案是你需要注入你的具體服務,正如我在我的回答中所說的,並且在這個實例中使用@Injectable()只是一個最佳實踐,並不是讓你的例子工作所必需的。 – nickspoon