angular - 无法在我的 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 时,我可以下载。
我在这里想念什么?
解决方案
首先在 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>
推荐阅读
- python - Python:删除类实例
- google-bigquery - 使用 BigQuery 解析字符串 - 格式为“121,131,111=1600”的实例
- arrays - 从字符串中解析变量并使用 Bash 将它们添加到数组中
- python - 在 href Beautifulsoup 之后解析文本
- python - 在python中查找特定分钟的下一次出现
- vb.net - VB.NET 应用程序性能分析 Visual Studio 2019
- python-3.x - 如何重置 .groupby 输出中的索引?
- scripting - autohotkey:按下 LButton 后取消 RButton 用户输入
- javascript - 2 slick carousel init 方法的问题
- android - 使用 Expo React Native 构建后,Android APK 无法正常工作