我一直在尝试通过传递诸如nameFilter = new FilterComponent("Name");
之类的参数来实例化组件,但出现此错误:
NullInjectorError:没有字符串提供程序!
我相信依赖注入会导致这种情况,因为如果我不向组件注入任何东西,那么我不会得到任何错误。那么究竟是什么原因导致的,我该如何解决呢?
这是组件代码
import { Component, OnInit, Inject } from '@angular/core';
@Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.scss']
})
export class FilterComponent implements OnInit {
title: String;
constructor(title: String) {
this.title = title;
}
ngOnInit() {
}
}
答案 0 :(得分:1)
该错误很明显,而您是对的,依赖项注入机制正在引起该错误。传递给构造函数的每个依赖项都必须在运行时注入,并且Angular需要知道要传递的内容。
在您的情况下,Angular不知道要作为字符串title
注入什么。
您可以显式告诉Angular在String类型的模块提供程序数组中注入什么。但是,这意味着每次在providers数组中提供的任何内容都将被使用。
@NgComponent({
...
providers: [
{ provide: String, useValue: 'my title' }
],
})
查看代码后,可以使用@Input
变量-Angular component interaction
export class FilterComponent implements OnInit {
@Input() title: string;
}
<app-filter [title]="Title 1"></app-filter>
答案 1 :(得分:0)
作为一种好的设计实践,避免在组件构造函数中注入原始数据类型,例如string
,number
,date
等。
但是如果您仍然需要注入它们。然后,您应该让Angular知道令牌和将要注入的值。
为此Angular提供了InjectionToken
API。 https://angular.io/api/core/InjectionToken#injectiontoken
在组件中注入日期类型的示例:
export const DATE = new InjectionToken<Date>('date');
@NgComponent({
...
providers: [
{ provide: DATE, useValue: new Date() } //can be declared at the module as well
],
})
export class SomeComponent {
constructor(
@Inject(DATE) private fromDate: Date,
@Inject(DATE) private toDate: Date
) {}
}