Angular 5:无法解析组件的所有参数

And*_* J. 9 dependency-injection angular5

我在使用angular 5中的注入服务时遇到了问题,如教程中所示.

我有一个简单的服务

@Injectable()
export class SimpleService {
    ...
}
Run Code Online (Sandbox Code Playgroud)

还有一个简单的组件:

@Component({...})
export class SimpleComponent {
    constructor(private simpleService SimpleService) {}
}
Run Code Online (Sandbox Code Playgroud)

服务设置为providers模块:

@NgModule({
    ...
    providers: [SimpleService]
    ...
})
export class SimpleModule {}
Run Code Online (Sandbox Code Playgroud)

我在控制台中看到以下错误:

Error: Can't resolve all parameters for SimpleComponent
Run Code Online (Sandbox Code Playgroud)

但是,如果我注入SimpleService@Inject

@Inject(SimpleService) private simpleService: SimpleService
Run Code Online (Sandbox Code Playgroud)

错误消失了.

我究竟做错了什么?

更新:我看到几个答案,人们建议添加emitDecoratorMetadata: true到tsconfig文件.但这条线已经存在

And*_* J. 6

原来,此错误的原因是错误导入polyfills.ts。以前,我弹出了cli应用程序,并从Webpack配置中删除了polyfills入口点。之后,我将它们导入到自己的计算机中main.ts。但是我进口后进口了填充料AppModule。在将import './polyfills.ts'语句移到文件顶部后,错误消失了。

解决此错误的另一种方法是移至AOT编译:

module: {
    rules: [
        ...
        {
            "test": /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
            "use": [
                "@ngtools/webpack"
            ]
        }
    ]
}
plugins: [
    ...
    new AngularCompilerPlugin({
        mainPath: 'main.ts',
        platform: PLATFORM.Browser,
        hostReplacementPaths: {
            'environments/environment.ts': 'environments/environment.ts'
        },
        sourceMap: true,
        tsConfigPath: 'src/app/tsconfig.json',
        skipCodeGeneration: false // this line is responsible for AOT
    })
]
Run Code Online (Sandbox Code Playgroud)

如果您使用AOT编译,而不是JIT,你将不再需要emitDecoratorMetadatatsconfig