我正在尝试将字符串注入到我的Angular组件中。 下面的代码可以正常工作,但它会给出一个弃用警告: get已被弃用:从v4.0.0开始使用Type或InjectionToken
@Component({
selector: 'app-label',
templateUrl: './label.component.html',
styleUrls: ['./label.component.scss']
})
export class LabelComponent {
public name: string;
public caption: string;
constructor(
private injector: Injector
) {
this.name = this.injector.get('name');
this.caption = this.injector.get('caption');
}
}
我尝试使用这份非常简短且不完整的文档Angular 5 Injector,来实现类似下面的功能,但是我不想使用useValue
或useClass
,我需要被注入的实际值。
class BS { }
// [..]
const name = new InjectionToken<string>('name');
const caption = new InjectionToken<string>('caption');
const injector = ReflectiveInjector.resolveAndCreate([
{ provide: name, useClass: BS},
{ provide: caption, useClass: BS}
]);
this.name = this.injector.get(name);
this.caption = this.injector.get(caption);
console.log(this.name); // will be an instance of BS
我在这里真的卡住了,文档完全没有帮助。
我需要这个用于动态组件加载和注入。完整的 Plunker 可以在此处找到:Plunker 动态组件加载和注入。
useValue
或useClass
? - Daniel W StrimpeluseValue
和useClass
提供者值只是告诉Angular您是否提供静态值或要实例化的类。这些看起来可能是UI字符串。您是否考虑过使用翻译库来注入这些字符串?一个例子是ngx-translate。 - Daniel W Strimpel