我在Angular应用程序中创建了一个REST API调用,用于下载文件.
我将responseType设置为’blob’,因为我期待响应中的文件.
但是当服务器上没有可用文件时,响应的错误代码为404,即错误请求,并且正文中有一些消息.
但我无法解析来自body的错误消息,因为HttpErrorResponse在error.error中给出了一个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:阅读完整的回复
相应地更改您的代码.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。