I have an Angular app that uses HttpClient for API calls. These return Observables of data types that I can use for various purposes, i.e. an Observable<Widget[]>
can be used to display a list of Widget search results.
Now, I have just coded up a backend/API endpoint that generates an Excel spreadsheet of some search results the user would like to download in that file format. I don't need any code in my component to interpret or process that data, I just want to link the user to that URL when he clicks a link. I want to use HttpClient because the Angular app is configured with an "HTTP interceptor" that adds a bearer token as an HTTP header, authorizing the user to the backend/API. I don't want to code the same thing in two places.
So, the question simply is: how can I use HttpClient in Angular to simply link the user to a URL? (Probably I would do this in a "new tab" i.e. target='_blank'
if that makes a difference to the answer.)
It's typical task: download files by link with auth bearer token. Simplest way to do it – download file as Blob and save it on client by a fake download link.
this.httpClient.get<Blob>('/api/.../xls').subscribe(blob => {
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = 'Any file name with extension.xls';
a.click();
document.body.removeChild(a);
});