javascript - 收到响应后更改 Angular (5)中的响应类型

标签 javascript json angular blob response

有没有办法在收到响应后更改 post 方法中的响应类型(angular 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? 提前致谢。

最佳答案

我相信你能做到:

 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;
      }
    })
  );

关于javascript - 收到响应后更改 Angular (5)中的响应类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52271107/

相关文章:

javascript - Javascript `userAgent` 与浏览器的 header 请求不同吗

javascript - React Native Chrome 自定义选项卡不起作用

javascript - 如何从 ember save 方法获取 JSON 响应

python - 使用python在postgresql数据库中插入json数据的问题

javascript - 在javascript中将并行字符串化(序列化)到JSON

javascript - Angular2 - 在路由和渲染组件之前通过服务获取数组

javascript - select2标签限制IE浏览器输入字符

angular - 如何防止 ng2-idle 在每次成功登录时多次实例化

Angular PWA 离线数据处理

javascript - 我想在 reactJs 中显示 JSON 结果