删除记录成功但NgRx触发失败Action的问题排查求助
删除记录成功但NgRx触发失败Action的问题排查求助
我现在在做一个用NgRx管理状态的Angular应用,碰到了一个奇怪的问题:明明删除记录的API调用已经成功了(数据库和文件系统里的目标记录都被删掉了),但NgRx的Effect却触发了失败Action,而不是预期的成功Action。控制台里的错误提示是:
can't parse JSON. Raw result: cancellazione avvenuta correttamente
(翻译:“删除操作已成功完成”)
我在Swagger里测试这个接口,返回的也是同样的内容。以下是整个删除流程的相关代码,麻烦大家帮我看看问题出在哪:
定义的NgRx Actions
export const removeResourceAttachment = createAction( '[Resource] Remove Resource Attachment', props<{ attachmentDto: AttachmentDto }>(), ); export const removeResourceAttachmentSuccess = createAction( '[Resource] Remove Resource Attachment Success', ); export const removeResourceAttachmentFailure = createAction( '[Resource] Remove Resource Failure', props<{ error: any }>(), );
NgRx Effects 代码
removeResourceAttachmentSuccess$ = createEffect(() => this.actions$.pipe( ofType(ResourceActions.removeResourceAttachmentSuccess), concatLatestFrom(() => this.store.select(ResourceSelectors.selectIdResourceToEdit)), mergeMap(([action, id]) => of(ResourceActions.loadResourceAttachmentsById({ resourceId: id!.toString() })), ), ), ); removeResourceAttachment = createEffect(() => this.actions$.pipe( ofType(ResourceActions.removeResourceAttachment), mergeMap((action) => this.resourceService .deleteResourceAttachmentByAttachmentId(action.attachmentDto.idAttached!) .pipe( map((response) => ResourceActions.removeResourceAttachmentSuccess()), catchError((error) => of(ResourceActions.removeResourceAttachmentFailure({ error }))), ), ), ), );
Angular 前端服务代码
deleteResourceAttachmentByAttachmentId(attachmentId: number): Observable<any> { return this.http.delete<any>(`${this.attachmentApi}/delete/${attachmentId}`); }
Java 后端Controller 代码
// 通过ID删除指定文件 @DeleteMapping("delete/{id_attached}") @PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER')") @Operation(summary = "Delete an attached file", description = "Delete an attached file", operationId = "DELETE_ATTACHED", responses = { @ApiResponse(responseCode = "201", description = "Successfully deleted"), @ApiResponse(responseCode = "400", description = "Invalid input provided"), @ApiResponse(responseCode = "500", description = "Error deleting the attached file") }) public ResponseEntity<String> deleteAttachedFile(@PathVariable(name = "id_attached") Integer idAttached) { attachedService.deleteFile(idAttached); return ResponseEntity.ok().body("cancellazione avvenuta correttamente"); }
Java 后端Service 代码
@Override public void deleteFile(Integer idAttached) { AttachmentEntity allegato = attachedRepo.findById(idAttached).orElseThrow(()->new EntityNotFoundException(" 无法找到ID为: " + idAttached + " 的附件")); attachedRepo.delete(allegato); Path filePath = Path.of(allegato.getPath()); try { Files.delete(filePath); log.info("文件已在以下路径删除: {}", filePath); } catch (IOException e) { log.error("删除文件时出错: {}", filePath); throw new RuntimeException("删除文件时出错: "+ filePath); } }
备注:内容来源于stack exchange,提问作者Giaggipc
相关产品推荐
相关产品推荐

