我有一个页面,在从返回给我的列表的 REST 服务获取数据后,我在循环中显示数据 DIV。每个 DIV 用于一次检查。加载数据后,当我单击一个 A+ 或 A- 来递增/递减数据时,我正在调用另一项服务。现在这个 REST 调用是从另一个组件完成的。 REST 服务只返回一项检查(不是检查列表)。因此,在收到 REST 的响应后,我想更新我单击的检查中的计数
Main.component.html
<p>Filter Data goes here</p>
<div class="wrapper">
<div class="box" *ngFor="let inspection of inspectionList let index=index; let odd=odd; let even=even">
<app-inspection [inspect]="inspection"></app-inspection>
</div>
</div>
主组件.ts
ngOnInit() {
this.http
.get('api/inspection/1')
.toPromise()
.then(response => {
let data = response.json();
if (data.inspectionList) this.inspectionList = data.inspectionList;
})
.catch(error => {
});
}
insp.component.html
<div class="row">
<div> {{inspect.inspectionDescription}} </div>
<table>
<tr>
<td><a [routerLink]="" (click)="updateCount(inspect.id, 1, 'AM')" class="btn btn-success">A-</a></td>
<td>{{inspect.rankAcount}}</td>
<td><a [routerLink]="" (click)="updateCount(inspect.id, 1, 'AP')" class="btn btn-danger">A+</a></td>
</tr>
现在,单击 A+ 或 A- 时,我正在调用 POST 服务(在另一个 component.ts 中)来更新数据库并返回结果。
insp.component.ts
updateCount() {
this.http
.post(url, params, {headers: this.headers})
.toPromise()
.then(response => {
let data = response.json();
if (data.rankAcount) alert(data.rankAcount);
})
.catch(error => {
});
}
现在我如何仅在一次检查中更新计数,而无需重新加载整个页面。
最佳答案
为什么你不会增加rankAccount来检查updateCount,如果POST失败,你只需递减它,对于递减操作,你将在点击时递减,失败时,你只需将其递增回来。
incrementCount(inspect, modelId, rank) {
inspection.rankAcount += rank;
updateCount({
inspectionId: inspect.id,
modelId: modelId,
rankChange: inspection.rankAcount
}).then(() => {
// etc.
}).catch(() => {
inspection.rankAcount -= rank;
});
}
decrementCount(inspect, modelId, rank) {
inspection.rankAcount -= rank;
updateCount({
inspectionId: inspect.id,
modelId: modelId,
rankChange: inspection.rankAcount
}).then(() => {
// etc.
}).catch(() => {
inspection.rankAcount += rank;
});
}
updateCount(params) {
this.http.post(url, params, {headers: this.headers}).toPromise();
}
或者像这样,但我会坚持使用 3 种方法。
updateCount(inspection, nr) {
inspection.rankAcount += nr;
this.http.post(url, params, {headers: this.headers}).toPromise().then(() => {
// etc.
}).catch(() => {
inspection.rankAcount -= nr;
});
}
updateCount(inspection, 1);
updateCount(inspection, -1);
关于javascript - Angular 4 : Refresh data in a div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49757338/