[英]Angular 2+ wait for subscribe to finish to update/access variable
我的變量未定義有問題。 我確定這是因為 observable 還沒有完成。 這是我的 .ts 文件中導致問題的代碼部分。 (我放置了理解問題所需的最少代碼myFunction
也從 HTML 中的點擊事件中調用)。
export class myClass {
myVariable: any;
myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
});
console.log(myVariable) --> undefined
}
}
因此,這段代碼調用了我的服務中的一個函數,該函數從 API 返回一些數據。 問題是當我嘗試在訂閱函數之外訪問變量myVariable
時,它返回未定義。 我確定這是因為在我嘗試訪問myVariable
之前訂閱尚未完成
在我嘗試訪問myVariable
之前,有沒有辦法等待訂閱完成?
為什么不創建一個單獨的函數並在訂閱中調用它。
export class myClass {
myVariable: any;
myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
this.update()
});
this.update()
}
update(){
console.log(this.myVariable);
}
}
如您所知,訂閱在服務器返回數據時執行,但訂閱代碼的外部同步執行。 這就是為什么執行它之外的console.log
的原因。 上面的答案可以完成您的工作,但您也可以使用.map
並return observable
,如下所示。
假設您從 s 服務調用它
export class myClass {
myVariable: any;
// calling and subscribing the method.
callingFunction() {
// the console log will be executed when there are data back from server
this.myClass.MyFunction().subscribe(data => {
console.log(data);
});
}
}
export class myClass {
myVariable: any;
// this will return an observable as we did not subscribe rather used .map method
myFunction() {
// use .pipe in case of rxjs 6
return this.myService.getApi().map(data => {
this.myVariable = data;
this.update()
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.