Angular 6 ResponseContentType

标签 angular rest api spring-boot xls

我正在尝试从我的 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 {

最佳答案

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

这也是传递 Auth Header 的示例。这不是必需的,但您可以查看 HttpClient 的 get 方法,了解更多关于如何构建它以通过其发送额外 header 的信息。

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

关于 Angular 6 ResponseContentType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51509190/

相关文章:

java - 试图在 Java 中测试矩形的交集,我做错了什么?

ios - 来源 http ://localhost:8100 is not allowed by Access-Control-Allow-Origin in ionic

javascript - Angular2 应用程序不适用于 Microsoft edge

rest - 2.4.0 中的 Apache CXF RS 扩展问题

android - 如何在 POST 请求中将 JSON 作为 BODY 从 Android 应用程序发送到服务器?

rest - Golang fasthttp 请求很慢

api - Web API 中的当前 PayPal 费用?

angular - 结合 *ngIf 管理子组件的最佳实践

html - 如何在 ionic 中获取输入文本值

angular - 在 Firebase 项目中共享 Typescript 接口(interface)