如何等待角度的for循环来响应?并更新响应的最新值。
users: Users
getUsers(){
this.userService.getUsers().subscribe(
(res: Users) => {
this.users = res
}
)
}
setValue(){
for (let i = 0; i < this.users.length; i++) {
if (this.users.length > 0) {
break
}
///some code
this.getUsers()
}
}
答案 0 :(得分:0)
如果您想在循环内调用API
,可以使用异步等待,这里是示例。
async setValue() {
for (let i = 0; i < this.users.length; i++) {
if (this.users.length > 0) {
break
}
///some code
await this.getUsers();
console.log(i); // here you can see that this line will execute after the api call is completed
}
}
getUsers(){
return new Promise(resolve => {
this.userService.getUsers().subscribe(
(res: Users) => {
this.users = res;
resolve();
}, err => {
resolve();
})
}
}