Angular 2(2.0.0 到 2.2.0~)在使用行 "import 'reflect-metadata'" 添加自定义装饰器时出错

Angular 2 (2.0.0 to 2.2.0~) getting error while adding custom decorator with the line "import 'reflect-metadata'"

在我基于 gulp 的项目中,我试图为数据验证实现一个自定义装饰器,但在某个时候我因为这个错误而陷入困境:

Error: Can't resolve all parameters for LoginService: (?, ?, ?).(…)

或者在其他情况下出现这样的错误:

Unexpected value 'AppComponent' declared by the module 'AppModule'

然后我开始做一些测试,我发现导致这个错误的行是:

import "reflect-metadata";

这里有两个版本的 tour-of-heroes 教程:

With the error caused by importing reflect-metadata.

And with the solution.

编辑

我已经通过添加 angular 的版本编辑了标题,我确信这个修复工作,从版本 1.3.0 我在使用装饰器时遇到问题,这就是为什么我要移动我的项目从 gulp 到 webpack

我在控制台有同样的错误

Error: Can't resolve all parameters for XXX: (?, ?, ?)

我找到了在 NgModule 上提供我的服务的解决方案 看我的回答

希望能帮到你

经过一天的调试 angular 和编辑我的代码,我找到了这个问题的解决方案,方法是在所有其他导入 之上添加另一个导入 :

import "reflect-metadata";

到错误中提到的 class,即使 class 没有使用 reflect-metadata 的任何 object:

例如 如果您遇到这样的错误:

Error: Can't resolve all parameters for LoginService: (?, ?, ?).(…)

Unexpected value 'AppComponent' declared by the module 'AppModule'

在 classes LoginService 和 AppComponent 添加 import 行以解决问题。

Here is a working version on Plunker.

编辑

我已经通过添加 angular 的版本编辑了标题,我确信这个修复工作,从版本 1.3.0 我在使用装饰器时遇到问题,这就是为什么我要移动我的项目从 gulp 到 webpack

基于 Lemmy4555 的回答(我没有代表发表评论),我能够通过添加

来解决这个问题
import "reflect-metadata";

到我的主要 angular 模块。我还不能解释到底出了什么问题,但是通过在其他地方导入库,似乎 angular 的装饰器中出现了问题,依赖注入无法正常工作。

这不是一个理想的解决方案,但在我看来,它比在弹出错误的地方导入它更干净。

我通过删除 import 'reflect-metadata'; 语句并通过 npm install @types/reflect-metadata --save-dev

Reflect 安装类型来修复类似的错误 (Unexpected value 'XXX' declared by the module 'AppModule')

另一个对我有用的选择是使用 Reflect 作为全局变量,根本不导入 reflect-metadata

有点像 declare const global: any; const Reflect = global['Reflect'];

引用https://blog.angularindepth.com/implementing-custom-component-decorator-in-angular-4d037d5a3f0d