Angular 6 ResponseContentType

问题描述 投票:3回答:1

我正在尝试从我的api休息中下载一些xls,但无济于事,我是否需要使用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 {
angular rest api spring-boot xls
1个回答
5
投票

下载文件的正确方法是使用responseType: 'blob'

这是一个传递Auth Header的例子。这不是必需的,但你可以看到HttpClient的get方法,了解如何构造它来发送额外的头文件。

//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>;

你可以在这样的组件中使用它。

    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);
    });
  }

我使用@ angular / common中的DatePipe使文件名唯一。

我还使用了文件保护程序来保存文件。

要通过在下面添加这些包来导入文件保护程序安装文件保护程序。

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

并在组件中添加import语句。

import { saveAs } from 'file-saver';
© www.soinside.com 2019 - 2024. All rights reserved.