How to get body from HttpErrorResponse in Angular 6?

后端 未结 5 824
予麋鹿
予麋鹿 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:32

    If the returned ContentType are different then you can leverage it to distinguish whether it's a correct binary file or a text in binary format.

    lets consider you have two files, a service, which handles your request and a component which does the business logic

    Inside your service, have your download method like:

     public downloadFile(yourParams): Observable {
            return this._http.post(yourRequestURL, yourParams.body, {responseType: 'blob'}).pipe(
                switchMap((data: Blob) => {
                    if (data.type ==  'application/octet-stream') {
                        // this is a correct binary data, great return as it is
                        return of(data);
                    } else {
                        // this is some error message, returned as a blob
                        let reader = new FileReader();
                        reader.readAsBinaryString(data);  // read that message
                        return fromEvent(reader, 'loadend').pipe(
                            map(() => {
                                return JSON.parse(reader.result); // parse it as it's a text.
                                // considering you are handling JSON data in your app, if not then return as it is
                            })
                        );
                    }
                })
            );
    }
    

    In your component

     public downloadFile(params): void {
            this._service.downloadFile(params)
                subscribe((data: yourType | Blob) => {
                    if (data instanceof Blob) {
                        fileSaverSave(data, filename);  // use fileSaver or however you are downloading the content
                        // add an import for saveAs (import { saveAs as fileSaverSave } from 'file-saver';)
                    } else {
                        // do your componnet logic to show the errors
                    }
                })    
        }
    

    If you wish, you can have everything inside your component itself.

提交回复
热议问题