typescript 获取状态代码http.获取响应angular2

6mw9ycah  于 2022-12-24  发布在  TypeScript
关注(0)|答案(6)|浏览(234)

我需要获取以下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);

}

谢谢!

exdqitrt

exdqitrt1#

添加Angular 〉= 4.3(包括11)版本的答案,新HttpClient替换了http

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'));
  });

正如@Rbk的评论所指出的,

对象{observe: 'response'}使完整响应对象可用。

Check Documentation

nwlls2ji

nwlls2ji2#

只需按如下所示修改代码,将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>
ecbunoof

ecbunoof3#

下面是代码:

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

}, error => {
      // You can access status:
      console.log(error.status);
});

上面的代码调用示例的subscribe()方法,然后在error通知中获取状态。

gk7wooem

gk7wooem4#

很简单!!
在extractData函数内部

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

vktxenjb5#

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

希望这能解决你的问题。

bf1o4zei

bf1o4zei6#

如果您使用的是HttpClient,请看以下示例:

this.http.post(myRequest, body, { headers : myHeaders, observe: 'response' }).subscribe(
  data => {
    console.warn(JSON.stringify(data, null, 2));
  },
  error => {
    console.error(error.errorMessage);
});

相关问题