收到响应后,以角度(5)更改responseType

时间:2018-09-11 07:47:59

标签: javascript json angular blob response

在收到响应后,是否可以通过 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? 预先感谢。

1 个答案:

答案 0 :(得分:2)

我相信您可以这样做:

(event.target as HTMLImageElement).src = ""