我在服務「MySharedService」已在「MyOutputTemp」的值有一個數據。我想在組件加載時將其顯示在組件中。從服務抓取數據,並在加載/組件中顯示它呈現:Angular2
這裏是我的組件:
@Component({
template: `....
<p>{{MyOutputHere}}
.....`
providers: [MySharedService]
})
export class MyOutputComponent implements OnInit{
MyOutputHere: string;
constructor (private _mySharedService: MySharedService){}
ngOnInit(){
console.log('Getting value from the service: ' + this._mySharedService.MyOutputTemp); //says undefined
this.MyOutputHere = this._mySharedService.MyOutputTemp;
console.log('Value in the component: ' +this.MyOutputHere);//says undefined
}
}
這裏是我的服務:
@Injectable()
export class MySharedService{
MyOutputTemp: string;
assignOutput(incomingParameter: string){
this.MyOutputTemp = incomingParameter;
console.log('Assigned value: ' + this.MyOutputTemp);
//the value is successfully assigned and I can get a print
} //I am calling it in another component. It is successfully assigning the value. Consider MyOutputTemp has value now.
}
我的嘗試:用ngOnInit(),以獲得從服務的價值,並把它放在「 MyOutputHere」。 發生了什麼:{{MyOutputHere}}顯示沒有值。如果我在控制檯中打印這個值,它會顯示「未定義」。
什麼那麼它在概念錯在這裏? 而且,如何從服務中獲取MyOutputTemp的值並將其顯示在組件中?
你有沒有叫'assignOutput'其中分配一定的參考價值'MyOutputTemp'。你應該先調用函數來設置它。 –
我在另一個組件中調用它。它正在成功分配值。考慮MyOutputTemp有價值。 –
是否在組件內觸發'ngOnInit'事件時查看該值是否已設置? –