我遵循了如何通过接口使用InjectionToken进行注入的文档。我刚做了一个小项目-
export interface MyInterface {
sayHello();
}
@Injectable()
export class MyService implements MyInterface {
sayHello()
{
throw new Error("Method not implemented.");
}
}我的app.module
export let MY_SERVICE = new InjectionToken<MyInterface>('MY_SERVICE');
providers: [
{
provide: MY_SERVICE,
useClass : MyService
}
],`这是app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(@Inject(MY_SERVICE) private myService : MyInterface) {
}
}这是我在Chrome工具中遇到的一个错误
编译器.es5.js:1690未明错误:无法解析AppComponent:(?)的所有参数。在CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getDependenciesMetadata的syntaxError (编译器.es5.js:1690),在CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getTypeMetadata (
发布于 2017-08-16 22:42:37
原码中的问题是,MY_SERVICE注入令牌实际上是在用于注入之后定义的。
为避免这种情况,应在此之前对其进行定义:
export let MY_SERVICE = new InjectionToken<MyInterface>('MY_SERVICE');
...
constructor(@Inject(MY_SERVICE) private myService: MyInterface) {
...或者,可以使用forwardRef助手,它的目的是避免出现这样的竞赛条件:
...
constructor(@Inject(forwardRef(() => MY_SERVICE)) private myService: MyInterface) {
...
export let MY_SERVICE = new InjectionToken<MyInterface>('MY_SERVICE');对于一个实际的应用程序来说,这通常不是一个问题,因为提供程序和使用它们的位置位于不同的模块文件中。
https://stackoverflow.com/questions/45722710
复制相似问题