我为接口创建了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