How to get body from HttpErrorResponse in Angular 6?

后端 未结 5 823
予麋鹿
予麋鹿 2020-12-11 17:14

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

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

But w

5条回答
  •  盖世英雄少女心
    2020-12-11 17:34

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

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

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

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

    this.configService.getConfigResponse()
        // resp is of type `HttpResponse`
        .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.');
    };
    

    import { catchError} from 'rxjs/operators';

    getConfig() { return this.http.get(this.configUrl) .pipe( catchError(this.handleError) ); }

    Reference: https://angular.io/guide/http : Reading the full response

    Change your code accordingly.

提交回复
热议问题