admin 管理员组

文章数量: 1086019

I'm working on an Angular application using NgRx to manage state. I have an action that deletes a record through an API call. The deletion is successful (the record is removed), but the NgRx effect triggers the failure action instead of the success action because of the response it gets:

can't parse JSON. Raw result: cancellazione avvenuta correttamente

(translation: "delete process successful")

I've tried it on Swagger as well, and I get the very same response, here's the code related to the whole process:

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 }>(),
);

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 }))),
          ),
      ),
    ),
  );

Front-end service:

  deleteResourceAttachmentByAttachmentId(attachmentId: number): Observable<any> {
    return this.http.delete<any>(`${this.attachmentApi}/delete/${attachmentId}`);
  }

Back-end controller:

  //Scarica il file desiderato tramite 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");
    }

Back-end service:

   @Override
    public void deleteFile(Integer idAttached) {
        AttachmentEntity allegato = attachedRepo.findById(idAttached).orElseThrow(()->new EntityNotFoundException(" impossibile trovare l'allegato con id:  " + idAttached));
        attachedRepo.delete(allegato);
        Path filePath = Path.of(allegato.getPath());
        try {
            Files.delete(filePath);
            log.info("File cancellato in: {}", filePath);
        } catch (IOException e) {
            log.error("Errore durante la cancellazione del file: {}", filePath);
            throw new RuntimeException("Errore durante la cancellazione del file: "+ filePath);
        }
    }

I'm working on an Angular application using NgRx to manage state. I have an action that deletes a record through an API call. The deletion is successful (the record is removed), but the NgRx effect triggers the failure action instead of the success action because of the response it gets:

can't parse JSON. Raw result: cancellazione avvenuta correttamente

(translation: "delete process successful")

I've tried it on Swagger as well, and I get the very same response, here's the code related to the whole process:

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 }>(),
);

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 }))),
          ),
      ),
    ),
  );

Front-end service:

  deleteResourceAttachmentByAttachmentId(attachmentId: number): Observable<any> {
    return this.http.delete<any>(`${this.attachmentApi}/delete/${attachmentId}`);
  }

Back-end controller:

  //Scarica il file desiderato tramite 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");
    }

Back-end service:

   @Override
    public void deleteFile(Integer idAttached) {
        AttachmentEntity allegato = attachedRepo.findById(idAttached).orElseThrow(()->new EntityNotFoundException(" impossibile trovare l'allegato con id:  " + idAttached));
        attachedRepo.delete(allegato);
        Path filePath = Path.of(allegato.getPath());
        try {
            Files.delete(filePath);
            log.info("File cancellato in: {}", filePath);
        } catch (IOException e) {
            log.error("Errore durante la cancellazione del file: {}", filePath);
            throw new RuntimeException("Errore durante la cancellazione del file: "+ filePath);
        }
    }
Share Improve this question edited Mar 27 at 11:13 Helen 98.3k17 gold badges276 silver badges346 bronze badges asked Mar 27 at 9:36 GiaggipcGiaggipc 211 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

You have two ways to fix this, I prefer the JAVA fix:

JAVA:

Return a json instead of plain text. Angular unless specified explicitly that the response is of type text does not handle text response properly.

  //Scarica il file desiderato tramite 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);
        Map<String, String> response = new HashMap<>();
        response.put("message", "cancellazione avvenuta correttamente");
        return ResponseEntity.ok().body(response);
    }

Angular:

Just set the response type in the http delete method second argument object.

deleteResourceAttachmentByAttachmentId(attachmentId: number): Observable<any> {
  return this.http.delete<any>(`${this.attachmentApi}/delete/${attachmentId}`, { 
    responseType: 'text' 
  });
}

本文标签: javaSuccessfully deleted a record but the response triggers an NgRx Action FailureStack Overflow