所以我注入(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
在 @NgModule
的 providers
数组中注册该 token ,将值映射提取到该 token
/p>
假设您编写了以下类,其中构造函数具有类型为 number
的 test
参数。在组件执行时,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/