title: Angular 2 download .CSV file click event with authentication
body: <p>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:</p>
  
  <p><strong>Typescript</strong></p>
  
  <pre><code>results(){
  window.location.href='myapicall';
  }
  </code></pre>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;button (click)="results()"
                      class="btn btn-primary"&gt;Export&lt;/button&gt;
  </code></pre>
  
  <p>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. </p>
  
  <p>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. </p>
  
  <p><strong>DownloadFileService</strong></p>
  
  <pre><code>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});
      }
  
  
  
  }
  </code></pre>
  
  <p>I tried downloading the data via a blob as suggested in this post:
  <a href="https://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2">How do I download a file with Angular2</a></p>
  
  <p>The file that gets downloaded is of type File and the content is:</p>
  
  <blockquote>
    <p>Response with status: 200 OK for URL:my url</p>
  </blockquote>
  
  <p>It doesn't actually download the data. </p>
  
  <pre><code>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 =&gt; this.downloadFile(data)),//console.log(data),
              error =&gt; console.log("Error downloading the file."),
              () =&gt; console.info("OK");
  
  
  
      }
  </code></pre>