获取状态码http.get response angular2

时间:2017-04-28 14:49:55

标签: angular typescript angular2-services http-status-codes

我需要获取以下http调用的状态代码并将其作为字符串

返回
//This method must return the status of the http response
confirmEmail(mailToken):Observable<String>{

     return this.http.get(this.baseUrl+"users/activate?mailToken="+mailToken)
                     .map(this.extractData)
                     .catch(this.handleError);

}

THX!

6 个答案:

答案 0 :(得分:8)

只需将您的代码修改为以下内容即可将responseStatus存储在字段中:

responseStatus: number;

//This method must return the status of the http response
confirmEmail(mailToken):Observable<String> {
//Edited for working with HttpClient on Angular >= 4.3
  return this.http.get(this.baseUrl+"users/activate?mailToken="+mailToken, {observe: 'response'})
                 .map((response: Response) => {
                   this.responseStatus = response.status;
                   return this.extractData(response);
                 }
                 .catch(this.handleError);

}

然后将其显示在组件HTML模板中:

<p class='responseStatus'>{{responseStatus}}</p>

答案 1 :(得分:8)

使用替换HttpClient

的新http为Angular&gt; = 4.3(包括7)版本添加答案
import {HttpClientModule} from '@angular/common/http'; // Notice it is imported from @angular/common/http instead of @angular/http

如何获取响应代码或任何其他标题:

http.get(this.baseUrl+"users/activate?mailToken="+mailToken, {observe: 'response'})
  .subscribe(response => {

    // You can access status:
    console.log(response.status);

    // Or any other header:
    console.log(response.headers.get('X-Custom-Header'));
  });

Check Documentation

答案 2 :(得分:3)

这就是我的做法:

checkResponse() {
  this.http.get(this.url, { observe: 'response' })
  .subscribe(response => console.log(response.status));
}

使用Angular 7。

答案 3 :(得分:2)

简单!!

在extractData函数中

extractData (res){
//res.status  will be your status code
// res.statusText  will be your status Text
}

答案 4 :(得分:0)

    confirmEmail(mailToken):Observable<String> {
   return this.http.get(this.baseUrl+"users/activate?mailToken="+mailToken)
     .pipe(map(data => {
       return data.httpStatus
         }));
     .catch(this.handleError);
}
  

希望,这将解决您的问题。

答案 5 :(得分:-1)

不与我合作

使用aspnet核心在c#中查看我的方法

    public IActionResult Insert([FromBody]TrocoSolidarioDTO x)
    {
        if (x == null)
        {
            return BadRequest();
        }
        try
        {
            return Ok("Working");
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }