Angular 5+Constructor字段注入器错误



所以我并不是简单地注入一个服务,只是试图用这样的构造函数初始化一些字段。

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;
}

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

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)

非常令人沮丧,因为我似乎找不到太多关于字段的注入问题,只有关于服务的问题。

您似乎正在向Angular的Component类传递参数,以便可以创建其实例new。但一旦你宣布它是有角度的@Component。在执行时,angular framework劫持了类constructor,并开始评估constructor的每个参数,并检查Dependency Injection内部的每个参数。基本上,它确实将每个参数的类型作为token传递给依赖注入系统。并针对@NgModuleproviders数组中的该令牌,基于provider寄存器提取到该token的值映射

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

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
) {
}

constructor((函数需要一个提供程序对象作为参数,因为"string"或"number"是angular类型。如果您只想初始化一些值,则必须将代码更改为以下类型:

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-nav-main',
templateUrl: './nav-main.component.html',
styleUrls: ['./nav-main.component.css']
})
export class NavMainComponent implements OnInit {
private wheels : number;
private model : string;
private automatic : boolean;
private colour : string;
private engine : string; 
private seats :number;
constructor() { }
ngOnInit() {
this.wheels = 4;
this.model = 'Model X';
this.automatic = false;
this.colour = 'Black';
this.engine = 'Engine Y'; 
this.seats = 5;
}
}

最新更新