我正在尝试订阅一个 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);
最佳答案
如果您将代码放在订阅回调中。它将在您收到后端的响应后执行。您在此函数之外编写的所有代码都将直接执行。
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
https://stackoverflow.com/questions/71420974/