【问题标题】:SyntaxError: JSON.parse: unexpected character on line 1 : Angular 5 Http call(Angular JS was working fine)SyntaxError:JSON.parse:第 1 行出现意外字符:Angular 5 Http 调用(Angular JS 工作正常)
【发布时间】:2018-03-21 04:25:20
【问题描述】:

我有一个提供字节数组的 Spring REST 服务。以前我使用的是 angularjs 1。使用 FileSaver,我能够下载 REST 服务根据 HTTP POST 调用的响应发送的 pdf。

现在,我正在将我的更改迁移到 Angular 5。这是我在服务中的 HTTP 发布调用 -

testPDF(abc: FormArray): Observable<HttpResponse<any>> {
    const options = {
        headers: new HttpHeaders({
            'Content-type': 'application/json',
             'response-type': 'blob'
       })
     }
     return this.http.post<HttpResponse<any>>('/myRestPath', abc, options);
}

在我的组件打字稿文件中,我已经像这样订阅了 -

xyz() {
    this.myService.testPDF(this.abc.value).subscribe((file: any) => console.log('done'));
}

我已经验证了我的 REST 服务。它返回正确的字节数组。我尝试了互联网上提供的其他几种解决方法。但似乎没有任何效果。在浏览器控制台中,我可以看到响应,它看起来是字节流中的 PDF。在控制台中,我可以看到收到了 3-4 MB 大小,这让我相信我已经收到了数据但无法订阅。 HTTP 响应码也是 200。

看起来默认情况下,响应被尝试作为 JSON 而不是 BLOB 获取。由于我的响应不是以“{”开头,因此在解析数据时它无法解析响应。我不是要求任何人为我编写代码。对于下载 PDF 文件,我可以使用 FileSaver 来完成。

我面临的关键问题是为什么我的应用程序没有进入订阅块并执行控制台语句。

【问题讨论】:

  • 显示abc方法myService;
  • 对不起。我的错。 Abc 方法是 testPDF 的一种。我已经更新了问题。

标签: json angular http rxjs angular5


【解决方案1】:

看起来您在headers 上设置响应类型,但HttpClient 期望它在optionsresponseType 属性上设置。

对于HttpClient,以下更新将起作用

testPDF(abc: FormArray): Observable<HttpResponse<Blob>> {
    return this.http.post('/myRestPath', abc, {
        observe: 'response',
        responseType: 'blob' 
    });
}

如果assets 目录下有一个名为some.pdf 的PDF 文件,则可以使用GET 为我提供一个完整的示例。

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class MyNewService {

  constructor(private http: HttpClient) { }

  getSomePDF():  Observable<HttpResponse<Blob>>{
    return this.http.get('/assets/some.pdf',  {
      observe: 'response',
      responseType: 'blob' 
    });
  }
}

对于使用@angular/http 的老用户,您可以使用ResponseContentType 枚举和import { ResponseContentType } from '@angular/http';

 const options = {
     responseType: ResponseContentType.Blob 
 }

API 文档here

【讨论】:

  • 当我像这样设置响应类型时,在将选项设置为 http 帖子的第三个参数时出现编译错误。它显示“属性'responseType'的类型不兼容。类型'string'不可分配给类型''json'”。
  • @pradiptagure 更新了答案以涵盖更多版本的 Angular。
  • 仍然有同样的问题。它仍然给出相同的编译错误。
  • 我使用的是最新版本的 angular。
  • @pradiptagure 你可以查看答案的最新更新
猜你喜欢
  • 2016-05-09
  • 1970-01-01
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
相关资源
最近更新 更多