javascript - Angular 5+构造函数字段注入(inject)器错误

标签 javascript angular typescript angular5

所以我注入(inject)的服务并不是简单地尝试使用这样的构造函数初始化一些字段。

  constructor(private wheels : number, private model : string, private automatic : boolean, private colour : string, private engine : string, private seats :number) { 
    this.wheels = wheels;
    this.model = model;
    this.automatic = automatic;
    this.colour = colour;
    this.engine = engine;
    this.seats = seats;
  }

如果我创建一个新对象,然后 console.log 该对象,我已经在没有 this.x=x 的情况下尝试过它,它具有所有初始值,但项目不会加载并给我这个错误消息。

ERROR Error: StaticInjectorError(AppModule)[Module1AComponent -> Number]: 
  StaticInjectorError(Platform: core)[Module1AComponent -> Number]: 
    NullInjectorError: No provider for Number!
    at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:1034)
    at resolveToken (core.js:1271)
    at tryResolveToken (core.js:1216)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1113)
    at resolveToken (core.js:1271)
    at tryResolveToken (core.js:1216)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1113)
    at resolveNgModuleDep (core.js:8161)
    at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:8849)
    at resolveDep (core.js:9214)

非常令人沮丧,因为我似乎找不到太多关于字段周围注入(inject)问题的信息,只能找到服务方面的信息。

最佳答案

看起来您正在将参数传递给 Angular 的 Component 类,这样它的实例就可以new创建了。但是一旦你将它声明为 angular @Component。在执行时,angular 框架劫持类 constructor,并开始评估 constructor 的每个参数,并检查 Dependency Injection 中的每个参数。基本上它确实将每个参数的类型作为 token 传递给依赖注入(inject)系统。并根据 provider@NgModuleproviders 数组中注册该 token ,将值映射提取到该 token/p>

假设您编写了以下类,其中构造函数具有类型为 numbertest 参数。在组件执行时,Angular DI 系统将尝试查找 number 提供程序的实例(确保单例实例,取决于注入(inject)器层次结构),然后为该实例提供服务。

constructor(private test: number)

也是

的简写
constructor(@Inject(number) private test)

虽然我不建议允许像您想要的那样手动创建 Angular 组件类实例。我不会说它行不通,但这不是好的做法。虽然使其工作的解决方法是在这些参数之前使用 @Optional() 装饰器。 @Optional如果在应用程序上下文的 Dependency Injector 容器中找不到值,基本上将返回 null 值。

constructor(
    @Optional() private wheels : number,
    @Optional() private model : string,
    @Optional() private automatic : boolean,
    @Optional() private colour : string,
    @Optional() private engine : string,
    @Optional() private seats :number
) {
}

关于javascript - Angular 5+构造函数字段注入(inject)器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51365330/

相关文章:

javascript - 在此函数中哪些值将返回 0?

javascript - getDate 返回错误值

javascript - componentDidMount() 中的 setTimeout() 不起作用

javascript - Youtube 嵌入式视频开始/停止事件

angular - 使用 RxJS forkJoin 时传递参数的最佳方法

javascript - 无法让 MockBackend 返回错误响应

javascript - 闭包:等效于 PHP "use"关键字或 Javascript 或转译器语言中的 C++ 捕获列表

angular - 选择对象数组内的嵌套对象数组

javascript - Nodejs 在使用循环下载许多文件时丢失数据

javascript - Angular 中的只读组件不显示换行符