簡體   English   中英

如何獲得角度7的響應代碼

[英]How do I get the response code in angular 7

我在角度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;

然而顯然現在不會返回一個可觀察的......這是一個問題嗎? (我對可觀察對象很新)返回一個observable而不僅僅返回Account []對象有什么好處?

為了完整起見,我正在使用響應構建我發送的標頭,如下所示

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

您需要通過選項observe: 'response'告訴Angular您想獲得完整的響應 ,這將使您可以訪問標題和狀態代碼:

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

響應的類型為HttpResponse<Account>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM