javascript – 如何从Angular 6中的HttpErrorResponse获取正文?
作者:互联网
我在Angular应用程序中创建了一个REST API调用,用于下载文件.
我将responseType设置为’blob’,因为我期待响应中的文件.
但是当服务器上没有可用文件时,响应的错误代码为404,即错误请求,并且正文中有一些消息.
但我无法解析来自body的错误消息,因为HttpErrorResponse在error.error中给出了一个blob对象
如何从错误对象而不是blob中获取实际正文.
也有任何方法配置角度,在api调用成功解析blob中的请求,否则解析它在json ???
希望得到解决方案
解决方法:
参数:{observe:’response’},让您阅读完整的回复,包括标题.见以下说明: –
使用observe选项告诉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(){
返回this.http.get< Config>(this.configUrl)
.管(
catchError(this.handleError)
);
}
参考:https://angular.io/guide/http:阅读完整的回复
相应地更改您的代码.
标签:angular-httpclient,javascript,angular 来源: https://codeday.me/bug/20190928/1825264.html