因此,我不是在尝试使用类似的构造函数初始化某些字段时才注入服务。
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)
非常令人沮丧,因为我似乎无法就围绕领域的注入问题找到很多糟糕的地方,仅就服务而言。
似乎您正在将参数传递给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
[constructor()函数期望提供者对象作为参数,因为“ string”或“ number”是类型angular会产生错误,如果您只想初始化一些值,则必须将代码更改为以下形式: