我一直在尝试遵循 ng-book 2 中的一个示例,但在 DI 章节中遇到了困难。
@Component({
selector: 'app-root',
template: `
<button (click)="invokeService()">Get Value</button>
`
})
export class AppComponent {
constructor(public myService: MyService) {}
invokeService() {
console.log(this.myService.getValue());
}
}
@Injectable()
export class MyService {
getValue(): string {
return 'a value';
}
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [MyService],
bootstrap: [AppComponent]
})
export class AppModule { }
这是一个 plunker https://plnkr.co/edit/KSXE9tnRj4tffiISyp0i它在手动创建 ReflectiveInjector 时完全有效,但是当我尝试采用简单的方法并在 NgModule 上的提供程序中声明它时,它失败给我“无法解决所有问题AppComponent 的依赖项”。我检查了其他答案,如您所见,没有循环依赖或与桶相关的问题 - 都在一个文件中。任何提示将不胜感激!