You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

删除记录成功但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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 20:08:13