首页 > 解决方案 > 无法在我的 Angular 应用程序中下载 pdf

问题描述

我有一个烧瓶 get api,只要点击 api,它就会下载一个 zip 文件。

api - https://example.com/downloads/user1

在我的 Angular 应用程序中,我放置了一个调用服务的下载按钮。

下载.service.ts

@Injectable()
export class downloadService extends BaseService {

protected modelUrl: string = 'downloads';

constructor(protected http: Http, protected _router: Router, protected _authService: AuthService) {
super(http, _router, _authService);
}

fetchDownloadUrl(body:any): Observable<Result> {
  return this.get(this.getUrl() + "/downloads/" + body);
} 
}

在我的 download.component.ts

function () {
    
    self.downloadService.fetchDownloadUrl(user).subscribe(
      response => {
        swal({
          position: "center",
          title: "Downloaded!",
          type: "success",
          timer: 1500,
          showConfirmButton: false
        });
      }

当我单击按钮时,它应该会点击服务中的 api。但我得到的是 pdf 作为响应,而不是在我的本地机器上下载。

另外,当我直接在我的 chrome 中点击 url 时,我可以下载。

我在这里想念什么?

标签: angularapifrontend

解决方案


首先在 fetchDownloadUrl 中,添加 httpOptions responseType。

下载.service.ts

fetchDownloadUrl(body:any): Observable<Result> {
   const httpOptions = {
      'responseType'  : 'blob' as 'json'
    };

  return this.get(this.getUrl() + "/downloads/" + body, httpOptions);
}

下载.component.ts

function () {
    
    self.downloadService.fetchDownloadUrl(user).subscribe(
      response => {
      downloadPdfFile(response)
        swal({
          position: "center",
          title: "Downloaded!",
          type: "success",
          timer: 1500,
          showConfirmButton: false
        });
      }
      
      
downloadPdfFile(data : any) {
    console.log(data)
    let file = new Blob([data], {type: 'application/pdf'});
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
  }

在您的 html 文件中的某处

<button (click)="download();">Download</button>

推荐阅读