当 API returns 204 状态代码时,httpclient 响应为空
httpclient response is null when API returns a 204 status code
我有一个休息端点 /Products/latest
returns 204 以防没有产品,以及以下通用 angular 服务:
getFromAPI(url: string) {
const params = new HttpParams();
return this.http
.get(url, { params: params })
.catch((err: HttpErrorResponse) => {
console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
return Observable.of([]);
});
}
和
getFromAPI() {
return this.masterService.get('/Products/latest').map((res: Response) => {
if (res.status === 204) {
return Observable.of([]);
} else {
return res;
}
});
}
但是,当服务生成 204 代码时,我收到以下错误:
TypeError: Cannot read property 'status' of null
怎么会这样?如果 API 以 204 响应,为什么整个响应为空?
首先,我要说的是 strange (or wrong) 您的后端为空集合返回 204 而不是 200 和空列表。
我使用 Angular7 和 RxJS6 构造了一个测试用例,其中我的后端配置如下:
[HttpGet("/Products/latest")]
public async Task<NoContentResult> list()
{
return NoContent();
}
在前端使用:
public getFromAPI() {
return this.httpClient.get('/Products/latest', { observe: 'response' }).pipe(
switchMap(res => res.status === 204 ? of([]) : of(res))
).subscribe();
}
尽管没有正文,但响应清楚地包含状态:
您的问题可能出在 this.masterService
上,它似乎在代理您的 http 客户端并吞噬了一些属性?
我有一个休息端点 /Products/latest
returns 204 以防没有产品,以及以下通用 angular 服务:
getFromAPI(url: string) {
const params = new HttpParams();
return this.http
.get(url, { params: params })
.catch((err: HttpErrorResponse) => {
console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
return Observable.of([]);
});
}
和
getFromAPI() {
return this.masterService.get('/Products/latest').map((res: Response) => {
if (res.status === 204) {
return Observable.of([]);
} else {
return res;
}
});
}
但是,当服务生成 204 代码时,我收到以下错误:
TypeError: Cannot read property 'status' of null
怎么会这样?如果 API 以 204 响应,为什么整个响应为空?
首先,我要说的是 strange (or wrong) 您的后端为空集合返回 204 而不是 200 和空列表。
我使用 Angular7 和 RxJS6 构造了一个测试用例,其中我的后端配置如下:
[HttpGet("/Products/latest")]
public async Task<NoContentResult> list()
{
return NoContent();
}
在前端使用:
public getFromAPI() {
return this.httpClient.get('/Products/latest', { observe: 'response' }).pipe(
switchMap(res => res.status === 204 ? of([]) : of(res))
).subscribe();
}
尽管没有正文,但响应清楚地包含状态:
您的问题可能出在 this.masterService
上,它似乎在代理您的 http 客户端并吞噬了一些属性?