【问题标题】:Angular 6 ResponseContentTypeAngular 6 响应内容类型
【发布时间】:2019-01-01 16:47:57
【问题描述】:

我正在尝试从我的 api rest 下载一些 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】:

下载文件的正确方法是使用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';

【讨论】:

  • resposneType 需要强制转换为 blob/arraybuffer/text 或任何允许的类型。 responseType: 'blob' as 'blob' 也是如此
猜你喜欢
  • 1970-01-01
  • 2019-04-15
  • 2011-01-21
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-03-10
  • 1970-01-01
  • 2014-12-07
相关资源
最近更新 更多