首页 > 解决方案 > 成功删除请求后如何接收 ResponseEntity

问题描述

在我的数据库中删除一个实体后,我将一个 ResponseEntity 从我的后端(SpringBoot)返回到我的前端(Angular 10)。因此,我在 Angular 中发出了这个 HTTP 请求:

this.http.delete<ResponseEntity<string>>(this.productsPath + '/' + id).subscribe(data => console.log(data.statusCode + data.body));    

为了接收响应,我创建了一个 ResponseEntity 接口:

interface ResponseEntity<T> {
headers: { [headerName: string]: string },
body: T,
statusCode: "OK" | "SERVER_ERROR" | "BAD_REQUEST", //etc
statusCodeValue: "200" | "500" | "400" | "404" //etc
}

现在在 SpringBoot 中,这是我的删除功能,它按预期工作:

@DeleteMapping(value = "/products/{id}")
public ResponseEntity<String> deleteProduct(@PathVariable String id) {
    try {
        productService.deleteProduct(Long.parseLong(id));
        return ResponseEntity.status(HttpStatus.OK).body("Product deleted successfully.");
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Product doesn't exist in Database.");
    }
}

我的问题出在我想的 Angular 代码中,我真的不知道如何从 Spring 获取响应?删除实体有效,但我在 Angular 中登录到控制台的响应始终为null,因此出现错误:ERROR TypeError: data is null

编辑:这个 SO 问题是我使用接口方法的原因:How to cast observable response to local object

标签: javascriptangularspring-boothttp

解决方案


推荐阅读