Angular 4.3: Getting an arraybuffer with new HttpClient

前端 未结 2 1951
挽巷
挽巷 2020-12-30 11:22

I would like to change to the new HttpClient. Until now I handle file downloads the following:

getXlsx (): Observable {
    return this.http.get(\         


        
2条回答
  •  再見小時候
    2020-12-30 12:04

    The above works and is an acceptable solution, however seems like a code smell just adding anchor tags to the DOM and faking a click when you can do it in a much cleaner way. We've recently had a similar issue for downloading documents in general from an Angular 5 website in which we have used FileSaver(https://www.npmjs.com/package/file-saver) .

    Adding FileSaver using npm install file-saver and doing the relevant imports you can use the following code to download a file:

    getDocument(document: Document) {
        let headers = new HttpHeaders(); // additional headers in here
    
        return this._http.get(url, {
            headers: headers,
            responseType: "blob" // this line being the important part from the previous answer (thanks for that BTW Martin) 
        }).map(
            res => {
                var x = res;
                if (res) {
                    let filename = documentName;
                    saveAs(x, filename);
                }
                return true;
            },
            err => {
                return true;
            }
        );
    } 
    

    This uses the native saveAs command if it exists and implements some other logic to replicate the functionality if it doesn't.

    This may do a similar thing under the hood (i don't really know as haven't had the change to look), but it compartmentalises it in an easy to use third party package that I would hope would be maintained (fingers crossed) without me having to update functionality to cater for newer versions of different packages / browsers.

提交回复
热议问题