在Angular 7中从POST请求中下载PDF文件,可以使用以下方法:
downloadService
的服务,并将其注入到需要下载文件的组件中。import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DownloadService {
constructor(private http: HttpClient) { }
downloadFile(url: string, data: any): void {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
const options = { headers, responseType: 'blob' as 'json' };
this.http.post(url, data, options)
.pipe(
map((res: any) => {
const blob = new Blob([res], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'file.pdf';
link.click();
})
)
.subscribe();
}
}
DownloadComponent
的组件,我们可以在该组件的方法中调用downloadService
来下载文件。import { Component } from '@angular/core';
import { DownloadService } from './download.service';
@Component({
selector: 'app-download',
templateUrl: './download.component.html',
styleUrls: ['./download.component.css']
})
export class DownloadComponent {
constructor(private downloadService: DownloadService) { }
downloadPdf(): void {
const url = 'http://example.com/download'; // 替换为实际的下载URL
const data = { key: 'value' }; // 替换为实际的POST请求数据
this.downloadService.downloadFile(url, data);
}
}
这样, 当用户点击按钮时,将通过POST请求从服务器下载PDF文件,并将其保存到本地。