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
1 Answer
Reset to default 0You 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
版权声明:本文标题:java - Successfully deleted a record but the response triggers an NgRx Action Failure - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744099306a2533421.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论