javascript - 如何从 Angular 6 中的 HttpErrorResponse 获取正文?
问题描述
我在下载文件的 Angular 应用程序中创建了一个 REST API 调用。
我将 responseType 设置为“blob”,因为我期待一个文件作为响应。
但是当服务器上没有可用的文件时,响应的错误代码为 404,即错误请求,正文中有一些消息。
但是我无法解析来自正文的错误消息,因为 HttpErrorResponse 在 error.error 中给出了一个 blob 对象
如何从错误对象而不是 blob 获取实际主体。
还有什么方法可以配置角度,在 api 调用成功时解析 blob 中的请求,否则在 json 中解析它???
希望有解决办法
解决方案
参数:{ observe: 'response' },让您阅读完整的响应,包括标题。请参阅以下说明:-
告诉 HttpClient 您想要使用观察选项的完整响应:
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(this.configUrl, { observe: 'response' });
}
现在 HttpClient.get() 返回一个类型化的 HttpResponse 的 Observable 而不仅仅是 JSON 数据。
this.configService.getConfigResponse()
// resp is of type `HttpResponse<Config>`
.subscribe(resp => {
// display its headers
const keys = resp.headers.keys();
this.headers = keys.map(key =>
`${key}: ${resp.headers.get(key)}`);
// access the body directly, which is typed as `Config`.
this.config = { ...resp.body };
});
并得到这样的错误主体:-
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
从'rxjs/operators'导入{catchError};
getConfig() {
return this.http.get<Config>(this.configUrl)
.pipe(
catchError(this.handleError)
);
}
参考:https ://angular.io/guide/http :阅读完整响应
相应地更改您的代码。