我正在嘗試訂閱 Observable 并從回應中分配一些資料,但不知何故我的代碼并沒有等待回應。基本上 console.log(this.newIds) 首先運行并且總是空的,因為訂閱不等待來自后端的回應。如何強制我的代碼等待回應的到來?
this.repository.getById(Ids).subscribe((response) => {
console.log(response);
this.newIds = response.map((id) => {
return id;
});
});
console.log(this.newIds);
uj5u.com熱心網友回復:
如果您將代碼放在訂閱回呼中。它將在您收到后端的回應后執行。您在此函式之外撰寫的所有代碼都將直接執行。
this.repository.getById(Ids).subscribe((response) => {
//Code will execute when back-end will respond
console.log(response);
this.newIds = response.map((id) => {
return id;
});
console.log(this.newIds);
});
//Code will execute immediately
另請參閱:https ://angular.io/guide/observables#creating-observables
uj5u.com熱心網友回復:
這是正常行為,因為您console.log(this.newIds);在訂閱之外,您只需將其移動到 .subscribe() 方法中:
this.repository.getById(Ids).subscribe((response) => {
console.log(response);
this.newIds = response.map((id) => {
return id;
});
console.log(this.newIds);
});
如果您想在訂閱之外使用 this.newIds 并且在觀察者的結果之后立即使用 RxJs .toPromise() 將其用作承諾并將方法更改為異步:
async callerFn(){
const response = await this.repository.getById(Ids).toPromise();
this.newIds = response.map((id) => {
return id;
});
console.log(this.newIds);
// use your property here
}
uj5u.com熱心網友回復:
是的,因為 Javascript 正在解釋逐行執行,因此它不會等待其他行程完成。這就是最后一個控制臺將回傳未定義的原因。同時,如果您在訂閱者內部使用控制臺,那么您將獲得正確的日志,因為訂閱者將等待回應并將其與 this.newIds 系結
this.repository.getById(Ids).subscribe((response) => {
console.log(response);
this.newIds = response.map((id) => {
return id;
});
console.log(this.newIds);
});
在這里,我附上了一篇關于可觀察訂閱的好讀物
https://betterprogramming.pub/observables-vs-promises-which-one-should-you-use-c19aef53c680
除此之外,如果您想在訂閱者范圍之外使用 newIds 訪問,請使用帶有異步等待的 Promise。在這里我添加一個示例
async getAsyncData() {
this.asyncResult = await this.httpClient.get<Employee>(this.url).toPromise();
console.log('No issues, I will wait until promise is resolved..');
}
uj5u.com熱心網友回復:
你可以這樣做..
您的組件檔案如下
newIds: Observable<any> = of(this.id).pipe(
concatMap((id) =>
this.getId(id).pipe(map((data) => data.map((rowId) => rowId.id)))
)
);
getId(id: any) {
return of([{ id: 1 }, { id: 2 }, { id: 3 }]);
}
您的 html 檔案如下所示,并使用異步管道進行訂閱。在這里,您可以使用 concateMap 管道 rxjs 運算子按順序呼叫 observable,然后將值分配給您的 newId 變數。
<pre>
{{ newIds | async }}
</pre>
此實時鏈接中的演示Stackblitz Link
uj5u.com熱心網友回復:
我會以不同的方式接近:如果你必須重新映射你可以使用map運算子的值:
this.repository.getById(Ids)
.pipe(map(response) => response.map(id => id))
.subscribe((id) => {
console.log(response);
this.newIds = id;
});
實際上,我不明白為什么你需要映射你已經擁有的值,但我認為這是明確的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442720.html
標籤:javascript 有角度的 打字稿 异步
