首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 10文件下载

Angular 10文件下载
EN

Stack Overflow用户
提问于 2020-12-31 12:50:34
回答 1查看 288关注 0票数 1

使用此函数接收数据的服务

代码语言:javascript
复制
  import { RequestOptions, ResponseContentType, Http } from '@angular/http';
import { map } from 'rxjs/operators';
    constructor(private http: Http) { }

    downloadFile(id): Observable<Blob> {
        let options = new RequestOptions({responseType: ResponseContentType.Blob });
        return this.http.get(this.baseUrl + `coursepurchased/receipt/` + bookingId, options)
        .pipe(map(res => res.blob()))
    }

组件使用“file-saver”分析blob

代码语言:javascript
复制
import {saveAs as importedSaveAs} from "file-saver";
 getCourseReceipt(bookingId) {
    this.studentInfoService.getCourseInvoice(bookingId).subscribe(
      blob => {
        var fileName = 'test.pdf';
        importedSaveAs(blob, fileName)
      },
      error => {
        console.log(error);
        this.alertService.showAlert(error.message, "error");
      }
    );
  }

这是我的angular 6版本下载代码..after,我已经升级到10 RequestOptions弃用/

请给我另一个解决方案..

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-31 13:15:22

这是的get方法(取自http.d.ts):

代码语言:javascript
复制
get<T>(url: string, options?: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable<T>;

因此,您可以执行以下操作:

代码语言:javascript
复制
downloadFile(id): Observable<Blob> {
    return this.http.get(this.baseUrl + `coursepurchased/receipt/` + bookingId, { responseType: "blob" });
}

该组件应如下所示:

代码语言:javascript
复制
getCourseReceipt(bookingId) {
    this.studentInfoService.getCourseInvoice(bookingId).subscribe(
      response => {
        var fileName = 'test.pdf';
        let blob:any = new Blob([response], { type: 'application/pdf; charset=utf-8' });
        importedSaveAs(blob, fileName)
      },
      error => {
        console.log(error);
        this.alertService.showAlert(error.message, "error");
      }
    );
  }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65516766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档