在Angular 2中下载PDF文件,通常涉及到以下几个基础概念:
npm install axios --save
import { Injectable } from '@angular/core';
import axios from 'axios';
@Injectable({
providedIn: 'root'
})
export class PdfService {
constructor() {}
downloadPdf(url: string): Promise<void> {
return axios({
url: url,
method: 'GET',
responseType: 'blob' // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf'); // or any other file name
document.body.appendChild(link);
link.click();
});
}
}
import { Component } from '@angular/core';
import { PdfService } from './pdf.service';
@Component({
selector: 'app-pdf-downloader',
template: `<button (click)="download()">Download PDF</button>`
})
export class PdfDownloaderComponent {
constructor(private pdfService: PdfService) {}
download() {
const pdfUrl = 'https://example.com/path/to/pdf'; // replace with your PDF URL
this.pdfService.downloadPdf(pdfUrl).catch((error) => {
console.error('Error downloading the PDF', error);
});
}
}
download
属性的值正确,并且服务器返回的PDF文件名与预期一致。URL.createObjectURL()
方法。确保目标用户使用的浏览器版本支持这些功能。通过以上步骤,你可以在Angular 2应用中实现PDF文件的下载功能。
领取专属 10元无门槛券
手把手带您无忧上云