问题描述
我正在开发一个使用 Angular CRUD 操作的网站,但我很难对我的数据库执行连续删除。
我恢复了需要从数据库中删除的 ID,该 ID 位于名为 « this.checkedLogs » 的数组中(这部分有效)。
然后,当我点击一个按钮时,我会调用一个用于执行这些删除的函数:« onModalConfirm »。
问题是它运行得如此之快,以至于我的迭代器没有时间更改它的值和要从函数已经循环的数组中删除的实际 ID。
此外,在循环结束时,条件 « if (this.checkedLogs.length == 0) » 不为真,这表明它进行得如此之快。
我正在考虑添加等待功能,但我不知道这是否符合良好做法。 我仍然是 Angular 的初学者,我对 Observable 的一切还不太熟悉。
- 这是我的 service.ts :
deleteLogsByID(id: number): Observable<any> {
return this._httpClient.delete(`${API_BASE_URL}/delete/id/${id}`,{responseType: 'text'});
}
- 这里是我的 component.ts :
deleteLogsByID(id: number): void {
this.logsSubscription = this.LogsService.deleteLogsByID(id).subscribe(
(data: any) => {
this.deleteMessage = data;
},(error: HttpErrorResponse) => {
this.showSpinner = false;
this.error = error.message;
this.showError = true;
}
);
}
onModalConfirm() {
/** Getting the length of my array by updating this.selectionAmount */
this.updateSelectionAmount();
/** If it’s not empty */
if (this.selectionAmount != 0) {
let iterator = this.checkedLogs.values();
for (let index = 0; index < this.selectionAmount; index++) {
/** Getting the id of the iterator */
let id: number = iterator.next().value;
/** Calling my delete function */
this.deleteLogsByID(id);
/** Removing the id from the array */
this.checkedLogs.splice(id,1);
}
/** When everything is done,reload the page */
if (this.checkedLogs.length == 0)
window.location.reload()
}
}
updateSelectionAmount() {
this.selectionAmount = this.selection.selected.length;
}
@ApiOperation(value = "Delete a logs by its id",produces = "application/json")
@PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')")
@DeleteMapping("/delete/id/{id}")
public ResponseEntity<String> deleteLogsById(@PathVariable Integer id) {
Integer idRemoved = logsService.deleteLogsById(id);
if (idRemoved == 0)
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
String responseReturn = "Logs removed with id " + id;
return new ResponseEntity<>(responseReturn,HttpStatus.OK);
}
提前致谢!
解决方法
是的,你说得对,for循环执行得很快,调用一堆请求,checkedLogs在请求执行前拼接。不知道您所有的应用程序逻辑,但我建议使用良好的旧回调来使删除操作具有顺序性。 onModalConfirm 将类似于:
onModalConfirm() {
/** Getting the length of my array by updating this.selectionAmount */
this.updateSelectionAmount();
/** If it’s not empty */
if (this.selectionAmount != 0) {
let iterator = this.checkedLogs.values();
const callDelete = () => {
let id: number = iterator.next().value;
const continueFn = (id) => {
if (id !== undefined) {
callDelete();
}
}
if (id !== undefined) {
this.deleteLogsByID(id,continueFn);
}
}
callDelete();
}
}
和 deleteLogsByID 将是:
deleteLogsByID(id: number,callbackFn: (id: number) => void): void {
this.logsSubscription = this.LogsService.deleteLogsByID(id).subscribe(
(data: any) => {
this.deleteMessage = data;
callbackFn(id)
},(error: HttpErrorResponse) => {
this.showSpinner = false;
this.error = error.message;
this.showError = true;
callbackFn(id);
}
);
}