【问题标题】:How do I get the response code in angular 7如何获取角度 7 中的响应代码
【发布时间】:2019-09-26 12:05:18
【问题描述】:

我在 Angular 7 应用程序中有以下代码

insertAccount(submittedAccount:Account):Observable<Account>{
    return this.http.post<Account>(this.baseApiUrl+"Account",submittedAccount,this.httpNormalOptions).pipe(
      map(response=>{
        return response;
      }
    ))
   }

如何获取 http 响应代码?例如,如果它返回 401 错误,我需要处理它,而目前它显然只是返回对象。

----更新----

好的,所以我遵循以下解决方案,但从未达到 map 方法,因为没有响应(我假设是因为 401 导致失败)

所以我改成下面这个

let result:Account[]=[];
    this.http.get<HttpResponse<Account[]>>(this.baseApiUrl+"Account",this.httpNormalOptions).pipe(map(
      response=>{
       return response;
      }
    )).subscribe(r=>{result= r.body},p=>{if(p.status===401){this.clearToken()}})

    return result;

但是显然现在不返回一个可观察的......这是一个问题吗? (我对 observables 很陌生)返回 observable 是否比简单地返回 Account[] 对象有好处?

为了完整起见,我正在构建与响应一起发送的标头,如下所示

this.httpNormalOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.auth_token,
          observe:'response'
        })
      }

【问题讨论】:

标签: angular typescript angular7


【解决方案1】:

您需要告诉 Angular 您想要使用选项 observe: 'response' 获取 complete response,这将使您能够访问标题和状态代码:

this.http.post<Account>(url, { observe: 'response' }).pipe(
    map(response => response.headers['status'])
)

响应类型为HttpResponse&lt;Account&gt;

【讨论】:

  • 我仍然只有一个帐户对象(即响应的类型为“帐户”)
  • @coolblue2000,响应的类型应该是HttpResponse&lt;Account&gt;
猜你喜欢
  • 2021-01-28
  • 2019-05-18
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
相关资源
最近更新 更多