问题描述
我正在从 html 调用一个方法(它调用一个休息服务)来增加/减少屏幕上的计数.现在我想调用另一种方法(即 getThreshold)来检查计数是否达到阈值.如果是,我想显示一条确认消息.
I am calling a method(which calls a rest service) from html to increment/decrement a count on the screen. Now I want to call another method (i.e. getThreshold) to check if the count reaches a threshold value. If yes I want to show a confirmation message.
我想先更新屏幕上的计数,然后调用函数检查它是否达到阈值.但是现在是先调用函数,再调用rest,然后更新屏幕上的计数.
I want to update the count on the screen first then call the function to check if it reaches the threshold. But now it is calling the function and rest call first, then updating the count on the screen.
在我拨打下一个休息电话之前,我必须显示一个确认对话框.但是在更新屏幕上的计数之前会出现对话框.
这是我的代码:
component.html
component.html
<table>
<tr>
<td><a [routerLink]="" (click)="updateCount(inspect, 'A', 'M')" class="btn btn-success">A-</a></td>
</tr>
</table
component.ts
component.ts
updateCount(inspection, rankName: string, rankPlusOrMinus: string) {
inspection.rankName = rankName;
inspection.rankPlusOrMinus = rankPlusOrMinus;
const url = '/api/xyz';
this.http
.post(url, JSON.stringify(inspection), {
headers: this.headers
})
.toPromise()
.then(response => {
let data = response.json();
if (rankName = 'A') inspection.rankAcount = data.rankAcount; ** // if I call getThreshold from here, it calls the function and rest call and displays alert message. But the count in A is NOT increamented yet**
})
.catch(error => {}
}
getThreshold(rankName: string, rankAcount: number) {
const url = '/api/threshold';
this.http
.get(url)
.toPromise()
.then(response => {
// Some Logic
// Show alert message
})
.catch(error => {});
}
}
推荐答案
您可以使用 flatMap 来订购 API:
You can use flatMap for ordering APIs as:
updateCount(inspection, rankName: string, rankPlusOrMinus: string) {
this.sendToServer(inspection, rankName, rankPlusOrMinus).flatMap((countResult) => {
// Here you can update your view
inspection.rankAcount = countResult.rankAcount;
return this.http.get('/api/threshold').subscribe(response => {
// Some Logic
// Show alert message
setTimeout(() => {alert('hi');});
});
}
}
);
}
sendToServer(inspection, rankName, rankPlusOrMinus) {
inspection.rankName = rankName;
inspection.rankPlusOrMinus = rankPlusOrMinus;
const url = '/api/xyz';
this.http.post(url, JSON.stringify(inspection), {headers: this.headers}).map((res: Response) => res.json());
}
解决方案 2
在第一个 API 响应后添加 timeout
:
add timeout
after first API's response:
...
if (rankName = 'A') inspection.rankAcount = data.rankAcount;
setTimeout(() => {
this.getThreshold(rankName, rankAcount);
});
...
这篇关于Angular:DOM 更新后的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!