Angular 2 download .CSV file click event with authentication

Bhetzie picture Bhetzie · Dec 5, 2016 · Viewed 31.3k times · Source

I'm using a spring boot backend and my api uses a service to send data via an OutputStreamWriter. I can download this in Angular 2 using a click event like so:

Typescript

results(){
window.location.href='myapicall';
}

HTML

<button (click)="results()"
                    class="btn btn-primary">Export</button>

This works just fine; however, I recently implemented security for my api endpoints and now I am receiving a 401 everytime I try to make the call because it's not sending a header.

I wrote a service that I can see the results in the console, but I can't seem to figure out how to download the file.

DownloadFileService

import {Injectable} from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class DownloadFileService {

    headers:Headers;
    bearer: string;
    constructor(public http: Http) {}



    getFile(url:string) {
        this.bearer = 'Bearer '+ localStorage.getItem('currentUser');
        this.headers = new Headers();
        this.headers.append('Authorization', this.bearer);

        return this.http.get(url, {headers: this.headers});
    }



}

I tried downloading the data via a blob as suggested in this post: How do I download a file with Angular2

The file that gets downloaded is of type File and the content is:

Response with status: 200 OK for URL:my url

It doesn't actually download the data.

downloadFile(data: any){
        var blob = new Blob([data], { type: 'text/csv' });
        var url= window.URL.createObjectURL(blob);
        window.open(url);
    }



    results(){
        // window.location.href='myapicall';   

         let resultURL =  'myapicall';

        this.downloadfileservice.getFile(resultURL).subscribe(data => this.downloadFile(data)),//console.log(data),
            error => console.log("Error downloading the file."),
            () => console.info("OK");



    }

Answer

shusson picture shusson · Dec 5, 2016

Looks like you just need to parse the body of the response i.e

let parsedResponse = data.text();
this.downloadFile(parsedResponse);

Also I would recommend you use FileSaver to download files as even in 2016 there does not seem to be a standard way to do this across browsers.

let blob = new Blob([data], { type: 'text/csv' });
saveAs(blob, "data.txt");

For a more in depth guide check here