我需要从后端下载一个excel,它返回了一个文件.

当我执行请求时,我会收到错误:

TypeError:您在需要流的地方提供了"undefined".你

我的代码是:

this.http.get(`${environment.apiUrl}/...`)
      .subscribe(response => this.downloadFile(response, "application/ms-excel"));

我试着找到 map (…)但没用.

详情:angular 5.2

参考资料:

import { HttpClient } from '@angular/common/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';

响应的内容类型:

Content-Type: application/ms-excel

发生了什么?

推荐答案

试试这样:

类型:应用程序/ms excel

/**
 *  used to get file from server
 */

this.http.get(`${environment.apiUrl}`,{
          responseType: 'arraybuffer',headers:headers} 
         ).subscribe(response => this.downLoadFile(response, "application/ms-excel"));


    /**
     * Method is use to download file.
     * @param data - Array Buffer data
     * @param type - type of the document.
     */
    downLoadFile(data: any, type: string) {
        let blob = new Blob([data], { type: type});
        let url = window.URL.createObjectURL(blob);
        let pwa = window.open(url);
        if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
            alert( 'Please disable your Pop-up blocker and try again.');
        }
    }

Typescript相关问答推荐

在TypScript手册中可以视为接口类型是什么意思?

类型脚本强制泛型类型安全

如何将联合文字类型限制为文字类型之一

类型脚本类型字段组合

无法绑定ngModel.条件ngSwitchCase中的错误

如何在Angular 12中创建DisplayBlock组件?

为什么T[数字]不也返回UNDEFINED?

为什么在这个例子中,我把缺少的属性添加到对象中时,TypeScrip没有拾取,如何修复?

<;T扩展布尔值>;

TypeScrip:来自先前参数的参数中的计算(computed)属性名称

是否可以判断某个类型是否已合并为内部类型?

如何缩小函数的返回类型?

在Cypress中,您能找到表格中具有特定文本的第一行吗?

如何静态键入返回数组1到n的函数

如何提取具有索引签名的类型中定义的键

在ts中获取级联子K类型?

我可以使用对象属性的名称作为对象中的字符串值吗?

Typescript 和 Rust 中跨平台的位移数字不一致

基于可选参数的动态类型泛型类型

在对象类型的类型别名中,属性是用分号 (;) 还是逗号 (,) 分隔的?