Using a Spring Boot backend, my API utilizes a service to send data through an OutputStreamWriter. In Angular 2, I can trigger a download by clicking on a button:
In Typescript
results(){
window.location.href='myapicall';
}
In HTML
<button (click)="results()"
class="btn btn-primary">Export</button>
While this method worked before, implementing security for the API endpoints is causing me to receive a 401 error every time due to missing headers.
I have created a service where I can see the results in the console, but I am struggling to figure out how to actually 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 attempted to download the file using a blob as advised in a StackOverflow post: How do I download a file with Angular2
The downloaded file appears as type File with content:
Response with status: 200 OK for URL: my url
However, the data is not actually being downloaded.
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");
}