首页 > 解决方案 > 如何根据Angular 8中的状态码转换响应体

问题描述

api 根据文件大小返回 2 个状态码。对于 200,它返回一个我已使用 transformImportCSVResponse() 转换为 Object 的 json 字符串。对于 201,它返回一个文本作为响应(“文件上传正在进行中”)

现在它对于 201 失败,因为它无法转换为 json

如何根据状态码处理两者。

this.httpClient.post(url, uploadedFile, {params: httpParams}).pipe(
      catchError(err => throwError(err)))
      .pipe(map(this.transformImportCSVResponse))

标签: angular

解决方案


问题是 200 和 201,实际上所有 2XX 响应都没有被视为错误。所以你可以做的是:

http
  .post<T>('/yoururl', whateverYourPostRequestIs, {observe: 'response'})
  .subscribe(resp => {
     console.log(resp);
  });

代码取自:How can get HttpClient Status Code in Angular 4

然后做if(resp.status === 200) { do thomething }

试试这个代码:

this.http.post(url, uploadedFile, {params: new HttpParams(), observe: 'response'})
  .subscribe(
    resp => {
      if (resp.status === 200) {
        this.transformImportCSVResponse(resp.body);
      }
    },
    error => console.log('oops', error)
  );

推荐阅读