2016-08-27 78 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