Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

Angular 10 file download

service with this function to recive the data

  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()))
    }

component parse the blob with 'file-saver'

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");
      }
    );
  }

This is my angular 6 version download code ..after i have updgraded to 10 RequestOptions deprecated/

Please help me alternative solution..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this is the get method for (taken from http.d.ts):

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

So you can do the following:

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

and the component should look like:

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");
      }
    );
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...