[英]how to check if a method api call is finished and then go to next step in angular
I have two methods in both I am doing api calls.我有两种方法我都在做 api 调用。 Method one is calling out method 2 and should continue with its process after method 2 api call is finished.
方法一是调用方法二,在方法二 api 调用完成后应继续其流程。 I tried to do this with the complete function inside subscription, but I am having the problem that method 2 is contiinuing doing its own work without waiting for method 2 to finish.
我尝试在订阅中使用完整的 function 来执行此操作,但我遇到的问题是方法 2 正在继续自己的工作,而无需等待方法 2 完成。 Can someone tell me where my mistake is?
有人能告诉我我的错误在哪里吗?
getPerson() {
this.setSelectedFlag() --> Whenever this finishes continue with method
this.personArray = this.form.controls.person.value;
this.personArray .forEach((id) => {
if (!this.personMap.has(id)) {
this.loading.start();
this.api.getpersonsData({
id,
}).subscribe((response) => {
this.personMap.set(id, response);
this.loading.stop();
});
}
});
this.personMap.forEach((person, id) => {
if (!this.personArray.includes(id)) {
this.personen.delete(id);
}
});
}
setSelectedFlag() {
this.personArray = this.form.controls.person.value;
this.personArray.forEach((id) => {
if (!this.setFlagForPerson.has(id)) {
this.personArraySaving.ids.push(id);
this.api.setSelectedForPerson({
body: this.personArraySaving,
}).subscribe({
next: (data) => {
console.log(data);
},
complete: () => {
return --> I thought this would signal its finish
},
});
}
});
}
Using promises would allow you to let setSelectedFlag() return a promise.使用承诺将允许您让 setSelectedFlag() 返回 promise。 After it returns you can continue with the code in getPerson()
返回后,您可以继续使用 getPerson() 中的代码
getPerson() {
this.setSelectedFlag().then(() => {
// rest of the code.
})
}
setSelectedFlag(): Promise<void> {
return new Promise((resolve) => {
....
complete: () => {
resolve();
}
})
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.