可能是响应类型不正确导致问题。如果使用HttpClient从服务端获取PDF文件,可以尝试设置响应类型为'blob'。代码示例:
import { HttpClient, HttpHeaders } from '@angular/common/http';
// 方法中获取PDF文件
getPdfFile() {
const headers = new HttpHeaders({'Content-Type': 'application/json', responseType: 'blob' });
return this.http.post('url/to/pdf', {}, { headers: headers, responseType: 'blob' });
}
通过在请求头中设置'Content-Type'为'application/json'和'responseType'为'blob'来请求PDF文件,然后在响应中接收'blob'格式,并使用window.URL.createObjectURL方法创建URL安全的Blob对象,就可以让浏览器打开PDF文件了。代码示例:
openPdf() {
this.getPdfFile().subscribe((response: Blob) => {
const fileURL = window.URL.createObjectURL(response);
window.open(fileURL);
});
}