我已经在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给了错误一个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 ???
希望获得解决方案
推荐答案参数: {观察:'response'} ,让您阅读完整的响应,包括标题.请参阅以下说明:-
Parameter: { observe: 'response' }, let you read the full response including the headers. See the below description:-
使用观察选项告诉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 }; });并得到这样的Error主体:-
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() { return this.http.get<Config>(this.configUrl) .pipe( catchError(this.handleError) ); }
getConfig() { return this.http.get<Config>(this.configUrl) .pipe( catchError(this.handleError) ); }
参考: angular.io/guide/http :阅读完整的回复
Reference: angular.io/guide/http : Reading the full response
相应地更改代码.
更多推荐
如何从Angular 6中的HttpErrorResponse获取主体?
发布评论