【问题标题】:Change responseType in angular (5) after receiving response收到响应后在角度(5)中更改 responseType
【发布时间】:2019-02-15 16:10:54
【问题描述】:

有没有办法在 post 方法中更改响应类型(角度 5)在收到响应后?
问题:当响应正常时我需要 responseType成为blob。如果没有 - 我需要 json responseType。
我进行了一些谷歌搜索,但找不到完全适合我情况的答案。
代码示例(简要):

// just simple method in service

export class MyService {

  constructor(private http: HttpClient) {}

  doSomething(data, fileName): Observable<any> {
    return this.http.post('url', data, {
      headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'),
      params: new HttpParams().set('fileName', fileName),
      responseType: 'blob'
    })
  }
}

// just classic method in component

export class MyComponent {

  constructor(private myService: MyService) {}

  this.myService.doSomething(this.data, this.file).subscribe(() => {
    // here doing something useful
  }, (error: HttpErrorResponse) => {
    // handling the error
  })
}

所以,再一次,在这种情况下,每次我都收到 blob 中的响应,如果一切都很好,那就太好了。但是如果我有错误,我需要在 json 中做出响应。反之亦然。
我如何在这两种情况下都设置正确的 responseType? 提前致谢。

【问题讨论】:

  • 在您的服务中使用 .map() 运算符
  • 您可以在错误处理程序中尝试JSON.parse(${error.error}) 吗?

标签: javascript json angular blob response


【解决方案1】:

我相信你可以做到:

 this.http.post('url', data, 
  { 
    observe: 'response',
    responseType: 'arraybuffer' ,
    headers: new HttpHeaders().set('Accept', 'application/octet-stream; application/json'), 
    params: new HttpParams().set('fileName', '') 
  })
  .pipe(
    map(res => {
      if (res.ok) {
        const blob:Blob = new Blob([res.body], {type: 'application/octet-stream'});
        return blob;
      }
      else {
        var decodedString = String.fromCharCode.apply(null, new Uint8Array(res.body));
        var obj = JSON.parse(decodedString);

        return obj;
      }
    })
  );

【讨论】:

  • 新的HttpClient没有blobjson方法
  • @David,谢谢,你是对的。我已经更新了答案。
  • 在这两种情况下使用该解决方案我在组件中都有错误...error.error 的类型为 ArrayBuffer (100) {}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 2018-06-19
  • 2021-01-06
  • 1970-01-01
相关资源
最近更新 更多