REST API的PDF未加载到Angular 2应用中 [英] PDF from REST API not loading into Angular 2 app
问题描述
为了使Angular 2/4应用程序成功地将RESTful http调用中的PDF文件加载到Web浏览器中,需要对以下内容进行哪些具体更改?
请注意,所涉及的应用程序扩展了http,以将JWT添加到http请求中.根据此链接,以这种方式扩展http会导致与覆盖RequestOptions相关的问题.
Note that the app in question extends http to add a JWT to http requests. According to this link, extending http in this way will cause problems related to overriding RequestOptions.
规格:
当用户在Web浏览器中键入http://192.168.1.5:4000/whitepaper.pdf
时,后端API成功提供了预期的PDF.但是,Angular应用程序需要以编程方式吸收API中的白皮书,然后使用包含在Angular应用程序中的URL在浏览器中提供pdf.
The intended PDF is successfully served by a backend API when users type http://192.168.1.5:4000/whitepaper.pdf
into a web browser. However, the Angular app needs to absorb the white paper from the API programattically, and then serve the pdf in the browser with a url that is part of the Angular app.
Angular应用程序的代码如下:
The code for the Angular app is as follows:
my.service.ts
getAll() {
console.log('Inside getAll!');
return this.http.get('http://192.168.1.5:4000/whitepaper.pdf').map((response: Response) => response.blob())
.catch((err:Response) => {
console.log('Error block!');
return Observable.throw('error!');
});;
}
my.component.ts
getPDF() {
console.log('Hey there, Jackass!');
console.log(JSON.parse(localStorage.getItem('currentUser')).token);
let myblob = new Blob([this.pDFService.getAll()], { type: 'application/pdf' });
console.log(myblob.type);
console.log(myblob.size);
var fileURL = URL.createObjectURL(myblob);
window.open(fileURL); // if you want to open it in new tab
}
myblob.type
打印为application/pdf
,myblob.size
打印为15
.
后端API在Node.js/Express中.
The backend API is in Node.js/Express.
Angular代码示例来自此答案,但在当前情况下不起作用.
The Angular code sample is from this answer, but does not work in the present situation.
The Code for the custom-http.ts
is at this link . The link mentions that problems will occur in the present circumstances when http is overridden as it is in the present app.
推荐答案
您的getAll()
向您返回Observable
.因此:
this.pDFService.getAll().subscribe( data => {
let myblob = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(myblob);
window.open(fileURL); // if you want to open it in new tab
})
这篇关于REST API的PDF未加载到Angular 2应用中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!