在Angular中解析时接收HTTP失败。目标是从api响应下载csv文件
控制器:
downloadFile(data) {
const blob = new Blob([data], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
getFileDownload(): void {
this.iportalUploadService.getFileDownload(this.fileName).subscribe(data => {
debugger;
this.fileDownload = data;
this.downloadFile(data);
});
}服务:
private fileDownloadUrl = 'file-transfer/validationErrorsCSV';
formHtppOptions(params): any {
const httpOptions = {
headers: { 'Application-Token': this.getToken() },
params: params,
};
return httpOptions;
}
getFileDownload(fileName): Observable < Object > {
const baseUrl = this.getBaseUrl();
return this.http.get<Object>(baseUrl + this.fileDownloadUrl, this.formHtppOptions({ fileName: fileName }));
}下面是我收到的console error控制台错误
响应格式照片Response photo
发布于 2018-07-17 11:33:01
您会收到此错误,因为您的响应不是JSON格式。您正在尝试将其转换为对象,而CSV文本无法解析为正确的json对象。下面是你可能想要做的事情:
getFileDownload(fileName): Observable<any> {
const baseUrl = this.getBaseUrl();
return this.http.get(baseUrl + this.fileDownloadUrl, this.formHtppOptions({fileName: fileName})).pipe(map((data:any) => this.converter.ToJson(data)));
}通常,我有一个执行这种解析的“转换器”服务。您可以使用papa parse,或者通过循环遍历响应来解析您自己。
更新:这里是一个手动解析响应的示例:http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html
请看上面的博客文章。
发布于 2018-07-18 22:13:36
我通过在formhttpOtions中添加responseType:'text‘解决了这个问题。
https://stackoverflow.com/questions/51372621
复制相似问题