Jun*_*sho 3 api rest xls spring-boot angular
我正在尝试从我的api rest下载一些xls,但无济于事,我是否需要使用ResponseContentType的东西?
[ts] O módulo '"/home/dev/Documentos/JAVA-TUDO/SIMPLUS/simplus-cliente/node_modules/@angular/common/http"' não tem nenhum membro exportado 'ResponseContentType'.
import ResponseContentType
import { Injectable } from '@angular/core';
import { HttpClient, ResponseContentType } from '@angular/common/http';
import { Product } from '../model/product.model';
@Injectable()
export class ProductService {
Run Code Online (Sandbox Code Playgroud)
下载文件的正确方法是使用responseType: 'blob'。
这也是一个传递Auth Header的示例。这不是必需的,但是您可以查看HttpClient的get方法,以了解更多有关如何构造它以发送其他标头的信息。
//service
public downloadExcelFile() {
const url = 'http://exmapleAPI/download';
const encodedAuth = window.localStorage.getItem('encodedAuth');
return this.http.get(url, { headers: new HttpHeaders({
'Authorization': 'Basic ' + encodedAuth,
'Content-Type': 'application/octet-stream',
}), responseType: 'blob'}).pipe (
tap (
// Log the result or error
data => console.log('You received data'),
error => console.log(error)
)
);
}
Run Code Online (Sandbox Code Playgroud)
HttpClient get()。
/**
* Construct a GET request which interprets the body as an `ArrayBuffer` and returns it.
*
* @return an `Observable` of the body as an `ArrayBuffer`.
*/
get(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
Run Code Online (Sandbox Code Playgroud)
您可以像这样在Component中使用它。
datePipe = new DatePipe('en-Aus');
onExport() {
this.service.downloadExcelFile().subscribe((res) => {
const now = Date.now();
const myFormattedDate = this.datePipe.transform(now, 'yyMMdd_HH:mm:ss');
saveAs(res, `${this.docTitle}-${myFormattedDate}.xlsx`);
}, error => {
console.log(error);
});
}
Run Code Online (Sandbox Code Playgroud)
我使用@ angular / common中的DatePipe来使文件名唯一。
我还使用了文件保护程序来保存文件。
要导入文件保护程序,请在下面添加以下软件包来安装文件保护程序。
npm install -S file-saver
npm install -D @types/file-saver
Run Code Online (Sandbox Code Playgroud)
然后在您的组件中添加import语句。
import { saveAs } from 'file-saver';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13068 次 |
| 最近记录: |