Angular 5+构造器字段注入器错误

问题描述 投票:4回答:2

因此,我不是在尝试使用类似的构造函数初始化某些字段时才注入服务。

  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)

非常令人沮丧,因为我似乎无法就围绕领域的注入问题找到很多糟糕的地方,仅就服务而言。

javascript angular typescript angular5
2个回答
6
投票

似乎您正在将参数传递给Angular的Component类,以便可以实例创建它的实例new。但是,只要您将其声明为角形@Component。在执行时,角度框架劫持了类constructor,并开始评估constructor的每个参数并检查Dependency Injection内部的每个参数。基本上,它确实将每个参数的类型作为token传递给依赖注入系统。并基于token

provider数组中该令牌的providers寄存器提取到@NgModule的值映射

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

constructor(private test: number)

也是]的简写>

constructor(@Inject(number) private test)

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

Dependency Injector

1
投票

[constructor()函数期望提供者对象作为参数,因为“ string”或“ number”是类型angular会产生错误,如果您只想初始化一些值,则必须将代码更改为以下形式:

© www.soinside.com 2019 - 2024. All rights reserved.