如何从 Angular 6 中的 HttpErrorResponse 获取正文? [英] How to get body from HttpErrorResponse in Angular 6?

查看:24
本文介绍了如何从 Angular 6 中的 HttpErrorResponse 获取正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Angular 应用程序中创建了一个 REST API 调用来下载一个文件.

I have created a REST API call in my Angular app which downloads a file.

我将 responseType 设置为 'blob',因为我期待一个文件作为响应.

I am setting responseType to 'blob' since I am expecting a file in response.

但是当服务器上没有可用的文件时,响应的错误代码为 404,即错误请求,正文中有一些消息.

But when there is no file available at the server the Response has a error code as 404 i.e Bad Request with some message in body.

但我无法解析来自正文的错误消息,因为 HttpErrorResponse 在 error.error 中提供了一个 blob 对象

But I am not able to parse that error message from body since HttpErrorResponse is giving a blob object in error.error

如何从错误对象而不是 blob 中获取实际正文.

How do I get the actual body from the error object instead of blob.

还有什么方法可以配置 angular,在 api 调用成功时解析 blob 中的请求,否则解析 json 中的请求???

Also is there any way to configure angular that on success of an api call parse the request in blob otherwise parse it in json ???

希望得到解决

推荐答案

参数:{ observe: 'response' },让您阅读包括标题在内的完整响应.请参阅以下说明:-

Parameter: { observe: 'response' }, let you read the full response including the headers. See the below description:-

用observe选项告诉HttpClient你想要完整的响应:

Tell HttpClient that you want the full response with the observe option:

getConfigResponse(): Observable<HttpResponse<Config>> {
    return this.http.get<Config>(this.configUrl, { observe: 'response' });
}

现在 HttpClient.get() 返回类型化 HttpResponse 的 Observable 而不仅仅是 JSON 数据.

Now HttpClient.get() returns an Observable of typed HttpResponse rather than just the JSON data.

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 };
    });

并得到这样的错误正文:-

and getting Error body like that:-

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};

import { catchError} from 'rxjs/operators';

getConfig() {返回 this.http.get(this.configUrl).管道(catchError(this.handleError));}

参考:https://angular.io/guide/http:阅读完整回复

相应地更改您的代码.

这篇关于如何从 Angular 6 中的 HttpErrorResponse 获取正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆