[英]How to return a value to the fuction that called the asynchronus code inside then and not the next then?
[英]How to store in Angular fuction return value into variable
我想將函數的返回值存儲到變量中。 我試過這個簡單的例子。
drawChart(){
var data = this.prepareData();
}
prepareData() {
return 1;
}
但是我收到了錯誤消息:
無法讀取未定義的屬性(讀取“prepareData”)
謝謝你的每一個幫助。
你必須調用drawChart()
的方法ngOnInit()
所以這個方法被調用,你可以從prepareData()
方法中獲取返回值
在這里,我為您的 ref 附加了 stackblitz 網址: stackblitz 代碼
希望能解決你的問題。
您需要將 drawChart() 和 prepareData() 放在 ngInit()、constructor() 之外和組件內部。
例如:
export class YourComponent implements OnInit {
ngOnInit() {
this.drawChart();
}
drawChart(){
var data = this.prepareData();
}
prepareData() {
return 1;
}
}
“this”關鍵字將指向類內的變量和函數,如果你在函數內聲明了這些函數,那將不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.