angular - Angular SyntaxError:位置 0 处 JSON 中的意外标记 P
问题描述
我正在尝试使用我的 Angular 应用程序下载一个 xls 文件,这在 Angular 8 之前已经有效,但突然不再有效。这是我到目前为止所拥有的:
export(selectedUsers: any) {
this.getReport(selectedUsers).subscribe(data => this.downloadFile(data));
}
private getReport(selectedUsers: number[]): Observable<Blob> {
const headers = new HttpHeaders({'content-type' : 'application/json',
'Access-Control-Allow-Origin' : '*',
responseType : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
return this.http.post<Blob>(this.globals.api + 'persoon/export', selectedUsers, {headers, 'blob'});
}
private downloadFile(data: Blob) {
console.log('downloading...');
const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
在它提到的角度文档中HttpEvent<Blob>
,我也尝试了这个,但它没有用。我尝试了这个类似的问题:HttpClient - How to request non-JSON data但是该解决方案也不起作用,因为它基本上说它不接受给定位置的 responseType。
我还检查了我的请求的响应头,内容类型也是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
这是我的进口:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Mail } from './models/mail';
import { Klant } from './models/klant';
import { GlobalsService } from './globals.service';
import { Observable } from 'rxjs';
谁能指出我正确的方向并帮助我解决这个问题?
应用接受的解决方案后,我遇到了另一个问题:
the expected type comes from property 'responseType' which is declared here on type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'
为此,您应该去这里:属性“responseType”的类型不兼容
解决方案
如您所引用的帖子中所述。responseType: 'blob'
不是标头,而是请求中的一个选项。所以你的请求应该是这样的:
private getReport(selectedUsers: number[]): Observable<Blob> {
const headers = new HttpHeaders({
'content-type' : 'application/json',
'Access-Control-Allow-Origin' : '*'
});
return this.http.post<Blob>(this.globals.api + 'persoon/export', selectedUsers, {headers, ResponseType: 'blob'});
}
推荐阅读
- javascript - 将坐标系应用于 3D 模型
- python - 问:AttributeError:模块“时间”没有属性“时钟”
- c# - 如何将平面模型映射到具有字符串属性和 IEnumerable 的类
使用自动映射器 - c# - 在 C# 中将一个对象分配给类的问题
- python - Arduino ide 上的“Nan”输出
- python - 如何在网页抓取中使用 br 标签以获得更好的输出?
- python - 使用 Python 读取二进制文件(fwrite C 输出)
- javascript - 在 Django 基于类的视图中定义任意函数并从前端调用它
- sql - 为什么使用 FIRST 和 LAST 方法不能解析由字符串索引的关联数组的所有内容
- c# - 如何正确配置 SmppServer?