[英]Angular - Waiting for backend call to finish and not skip
New to angular and I have this issue I have been trying to solve. angular 的新手,我一直在努力解决这个问题。 I have looked all around for a solution but with no luck for my situation.我四处寻找解决方案,但我的情况没有运气。
so here is my problem.所以这是我的问题。
I have a call to back end.我打电话给后端。
private setDocId(document: Document){
this.api.getInfo(randomNumber: number).subscribe(data => {
if (data === 1) {
document.id = data;
}
})
}
regular validation check定期验证检查
private checkIfDocExists(document: Document){
return document.isExists ? document.approved = true : document.approved = false:
}
validation both methods验证两种方法
private isValid(): boolean {
this.setDocId(document);
const isExists = this.checkIfDo1cExists(document);
return isExists && document.id !== null;
}
as you can see last method returns validation if both conditions are true;如您所见,如果两个条件都为真,最后一个方法将返回验证; both condition are true, however since the backend call does not wait and continues it returns false since it has not completed initialization yet.两个条件都为真,但是由于后端调用不等待并继续它返回假,因为它还没有完成初始化。
is there a way to let first method (with api call to back end) to wait to finish before it continues?有没有办法让第一个方法(api 调用后端)在继续之前等待完成? without using setInterval or setTimeout?不使用 setInterval 或 setTimeout?
thanks.谢谢。
You can use async
and await
to let the first method complete first.您可以使用async
和await
让第一个方法先完成。
private async setDocId(document: Document){
const data = await this.api.getInfo(randomNumber: number).toPromise();
if (data === 1) {
document.id = data;
}
}
private isValid(): boolean {
await this.setDocId(document);
...
}
I think you could get this to work by using a BehaviorSubject and performing the check inside setDocId
.我认为您可以通过使用 BehaviorSubject 并在setDocId
中执行检查来使其工作。
private isValidSubject = new BehaviorSubject<boolean>(false);
isValid$ = this.isValidSubject
private setDocId(document: Document): void {
this.api.getInfo(randomNumber)
.pipe(
map(data => {
if (data === 1) {
document.id = data;
const isExists = this.checkIfDo1cExists(document);
this.isValidSubject.next(isExists && document.id !== null);
}
}),
).subscribe();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.