首页 > 解决方案 > 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”的类型不兼容

标签: angulartypescript

解决方案


如您所引用的帖子中所述。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'});
  }

推荐阅读