Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

javascript - How to get body from HttpErrorResponse in Angular 6?

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 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.

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

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

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 ???

Hoping for a resolution

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<HttpResponse<Config>> {
    return this.http.get<Config>(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<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.');
};

import { catchError} from 'rxjs/operators';

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

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

Change your code accordingly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...