Angular 6 ResponseContentType

Junior Osho picture Junior Osho · Jul 25, 2018 · Viewed 22.5k times · Source

I'm trying to download some xls from my api rest, but to no avail, do I need something to use ResponseContentType?

[ts] O módulo '"/home/dev/Documentos/JAVA-TUDO/SIMPLUS/simplus-cliente/node_modules/@angular/common/http"' não tem nenhum membro exportado 'ResponseContentType'.


import ResponseContentType
import { Injectable } from '@angular/core';
import { HttpClient, ResponseContentType } from '@angular/common/http';
import { Product } from '../model/product.model';

@Injectable()
export class ProductService {

Answer

Mukus picture Mukus · Aug 16, 2018

The correct way to download a file is to use responseType: 'blob'.

Here's an example of passing Auth Header as well. This is not necessary, but you can see the HttpClient's get method for more on how to construct this to send additional headers through.

//service
public downloadExcelFile() {
const url = 'http://exmapleAPI/download';
const encodedAuth = window.localStorage.getItem('encodedAuth');

return this.http.get(url, { headers: new HttpHeaders({
  'Authorization': 'Basic ' + encodedAuth,
  'Content-Type': 'application/octet-stream',
  }), responseType: 'blob'}).pipe (
  tap (
    // Log the result or error
    data => console.log('You received data'),
    error => console.log(error)
  )
 );
}

HttpClient get().

 /**
 * Construct a GET request which interprets the body as an `ArrayBuffer` and returns it.
 *
 * @return an `Observable` of the body as an `ArrayBuffer`.
 */
get(url: string, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType: 'arraybuffer';
    withCredentials?: boolean;
}): Observable<ArrayBuffer>;

You can consume this in the Component like this.

    datePipe = new DatePipe('en-Aus');

    onExport() {
    this.service.downloadExcelFile().subscribe((res) => {
      const now = Date.now();
      const myFormattedDate = this.datePipe.transform(now, 'yyMMdd_HH:mm:ss');
      saveAs(res, `${this.docTitle}-${myFormattedDate}.xlsx`);
    }, error => {
      console.log(error);
    });
  }

I used DatePipe from @angular/common to make the filename unique.

I also used file-saver to save the file.

To import file-saver install file-saver by adding these packages below.

npm install -S file-saver
npm install -D @types/file-saver

And the in your component add the import statement.

import { saveAs } from 'file-saver';