2016-08-27 79 views
0

我爲接口創建了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"); 
    } 
} 

回答

2

要使用依賴注入,您需要使用@Injectable裝飾器標記服務。此外,您將無法注入界面,您需要注入您提供的課程。

@Injectable() 
class ErrorService implements MyInterface { 
    public log(msg: string) { 
     console.error(msg); 
    } 
} 
@Component({ 
    selector: 'my-child', 
    template: `<h4 (click)="log()"> Hello Child</h4>`, 
    providers: [ErrorService] 
}) 
export class ChildComponent { 
    constructor(private dummy: ErrorService) {} 
    log() { 
     this.dummy.log("Child"); 
    } 
} 
0

Angular website「的接口是可選的用於從純技術的角度JavaScript和打字稿開發。JavaScript語言沒有接口。角看不到打字稿界面在運行時,因爲他們從消失轉譯JavaScript。「

由於這個原因,我們不能使用接口來請求具體的實現。

@Injectable()不是DI工作所需的裝飾器。只有當服務依賴於其他服務時,它才被裝飾在服務類別上。

+0

這是不正確的。 @Injectable()*是DI工作所必需的,正如它在[@angular documentation]中所述(https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#injectable) :_「@ Injectable()將一個類標記爲可用於實例化的注入器。一般而言,當試圖實例化未標記爲@Injectable()的類時,注入器將報告錯誤。」_ – nickspoon

+1

@nickspoon - an從您提供的文檔鏈接中抽象​​出來,「我們建議將Injectable()添加到每個服務類,即使那些沒有依賴關係,因此在技術上也不需要它。」僅當服務依賴於其他服務時才需要注入裝飾器。 Angular文檔清楚地表明這不是必需的,但即使服務類沒有依賴關係,它也是用Injectable()來裝飾服務類的「約定」。 – user1176058

+0

對不起,你是對的,我剛剛測試過,沒有依賴關係的服務可以在沒有'@Injectable()'的情況下注入。所以你的問題的答案是你需要注入你的具體服務,正如我在我的回答中所說的,並且在這個實例中使用@Injectable()只是一個最佳實踐,並不是讓你的例子工作所必需的。 – nickspoon