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

Mun*_*erz 4 javascript typescript angular angular5

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

  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;
  }
Run Code Online (Sandbox Code Playgroud)

如果我现在创建一个新对象,然后在 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)
Run Code Online (Sandbox Code Playgroud)

非常令人沮丧,因为我似乎找不到很多关于领域注入问题的内容,只有关于服务。

Pan*_*kar 9

似乎您正在将参数传递给 Angular 的 Component 类,以便可以创建它的实例new。但是一旦你将它声明为 angular @Component。在执行时 angular 框架劫持了类 constructor ,并开始评估 constructor 和检查里面的每个参数Dependency Injection。基本上它确实将每个参数的类型作为token依赖注入系统传递。并token根据数组中provider该令牌的寄存器将值映射提取到providers@NgModule

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

constructor(private test: number)
Run Code Online (Sandbox Code Playgroud)

也是简写

constructor(@Inject(number) private test)
Run Code Online (Sandbox Code Playgroud)

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

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
) {
}
Run Code Online (Sandbox Code Playgroud)