我使用值提供程序使用此组件:
import { Component, OnInit, Injector } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [{
provide: "currency",
useValue : "dollar"
}]
})
export class AppComponent implements OnInit {
ngOnInit(): void {
}
title = "app works";
constructor(private injector: Injector){
this.title = "Currency is: "+ injector.get("currency");
}
}
当我运行程序时,进样器会抛出一个错误," Cannot read property 'instance' of undefined
"
如果重要,我的观点很简单<h1>{{title}}</h1>
。
我做错了什么?
答案 0 :(得分:1)
不要使用Injector,只需导入'Inject'装饰器并使用如此 -
import { Component, OnInit, Inject } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [{
provide: "currency",
useValue : "dollar"
}]
})
export class AppComponent implements OnInit {
ngOnInit(): void {
}
title = "app works";
constructor(@Inject("currency") private currency){
this.title = "Currency is: "+ currency;
}
}