Angular 7 - 使用 FileSaver.js 下载 Excel 文件无效

Angular 7 - using FileSaver.js to download an Excel file not working

我正在向后端发送 post 请求以接收 Excel 文件。我可以在 postman 中看到我的后端正在发送 Excel,但在 Angular 中,我无法使用 FileSaver.Js 库下载它。有任何想法吗?

这是我的 html 标记:

<button (click)="excel()">Export Excel</button> 

这是我的服务class:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import * as FileSaver from 'file-saver';
import 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
    constructor(private data: DataService , private formBuilder: FormBuilder ) { }

    ngOnInit()  {
    }

    excel() {
        this.data.excel().toPromise()
            .then(response => this.saveToFileSystem(response));
    }

    private saveToFileSystem(response) {
        const contentDispositionHeader: string = response.headers.get('Content-Disposition');
        const parts: string[] = contentDispositionHeader.split(';');
        const filename = parts[1].split('=')[1];
        const blob = new Blob([response._body], { type: 'text/plain' });

        FileSaver.saveAs(blob, filename);
    }
}

这里是我的数据class请求后端的方法:

excel() {
    const headers = new HttpHeaders();
    console.log("sentin")
    headers.set('Content-Type', 'application/json; charset=utf-8');
    return this.http.post(this.baseUrl + '/Excel', { headers: headers })
}

终于有了答案:

我应该做出这些改变:

  1. 将方法saveFileSystem改为:

    private saveToFileSystem(response) {
        const blob = new Blob([JSON.stringify(response.body)], { type: 'application/vnd.ms-excel;charset=utf-8' });
        FileSaver.saveAs(blob, "Report.xls");
    }
    
  2. 像这样向我的 HttpPost 添加响应类型:

    { responseType: 'text' }