如何从角度5的网址下载pdf文件

pra*_* vv 6 angular5

我目前在这个问题上花了一天时间,仍然无法从角度5的网址下载文件

leadGenSubmit() {

    return this.http.get('http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf',
    {responseType:ResponseContentType.Blob}).subscribe((data)=>{
        console.log(data);
        var blob = new Blob([data], {type: 'application/pdf'});
        console.log(blob);
        saveAs(blob, "testData.pdf");
    },
    err=>{
        console.log(err);
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,它显示以下错误

ERROR TypeError: req.responseType.toLowerCase is not a function
    at Observable.eval [as _subscribe] (http.js:2187)
    at Observable._trySubscribe (Observable.js:172)
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题.任何人都可以发布正确的代码从角度5的网址下载pdf文件?

och*_*obi 13

我认为你应该像这样定义header和responseType:

let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' });
Run Code Online (Sandbox Code Playgroud)


jpm*_*tin 8

这是我在 Angular 中根据 ID 打开 PDF 的简单解决方案:

在我的服务中,我创建了这个方法:

public findById(id?: string): Observable<Blob> {
  return this.httpClient.get(`${this.basePath}/document/${id}`, {responseType: 'blob'});
}
Run Code Online (Sandbox Code Playgroud)

然后在我的组件中,我可以使用这个方法(在按钮后面或其他地方):

showDocument(documentId: string): void {
  this.yourSuperService.findById(documentId)
    .subscribe((blob: Blob): void => {
      const file = new Blob([blob], {type: 'application/pdf'});
      const fileURL = URL.createObjectURL(file);
      window.open(fileURL, '_blank', 'width=1000, height=800');
    });
}
Run Code Online (Sandbox Code Playgroud)


Sur*_*ala 5

尝试这个

let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' as 'json' });
Run Code Online (Sandbox Code Playgroud)

参考: