簡體   English   中英

如何獲取 http 請求的響應狀態? Angular

[英]How to get the response status of an http request? Angular

我需要你的幫助。 我有一小段代碼用於調用服務並執行post請求。 事實是我需要從請求中獲取響應的狀態。 事實是我訂閱了來自服務的請求,我需要專門為我的應用程序鍵入它,但我無法獲得狀態。 告訴我我做錯了什么? 非常感謝

在組件中

this.service.sendParams(constConnectBody).subscribe((profile: IProfile) => {
   this.profile = profile;
}, (res) => console.log(res.status)); // nothing

在役

public sendParams(body: any):Observable<any> {
   return this.httpClient.post<any>(`this.url`, body)
}

或在服務中

responseStatus: any

public sendParams(body: any):Observable<any> {
   return this.httpClient.post<any>(`this.url`, body, {observe: response}).pipe(map(res => this.responseStatus = res.status))
}

HttpClient 方法接受一個選項參數,其中可以包括observe: 'response'以返回完整響應,而不僅僅是響應正文。

return this.httpClient.post<any>('this.url', body, {observe: 'response'})

詳見https://angular.io/api/common/http/HttpClient#options

根據您的評論,您可以這樣做

responseStatus: any

public sendParams(body: any):Observable<IProfile> {
   return this.httpClient.post<IProfile>(this.url, body, {observe: 'response'}).pipe(map(res => {
      this.responseStatus = res.status;
      return res.body;
   }));
}

暫無
暫無

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

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