我们如何在Angular 4中获取HttpClient状态代码

时间:2018-06-19 04:50:46

标签: angular

Hiular for Angular,我遇到了获取HTTP状态代码的问题,在HTTP模块中我可以使用 response.status 轻松获取响应代码,但是当我使用HttpClient时模块我无法获得response.status,它显示无法找到状态。

那么,如何在HttpClient中使用Angular 4&5模块获取response.status。请帮忙。

RestProvider: -

@Injectable()
export class RestProvider {

  private apiUrl = 'https://restcountries.eu/rest/v2/al';

  constructor(public http: HttpClient) {
    console.log('Hello RestProvider Provider');
  }

  getCountries(): Observable<{}> {
    return this.http.get(this.apiUrl).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

  private extractData(res: Response) {
    let body = res;
    return body || { };
  }

  private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const err = error || '';
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}

主页:

export class HomePage {

  responseStatus: number;

  countries: any;
  errorMessage: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, public rest: RestProvider) {
  }

  ionViewDidLoad() {
    this.getCountries();
  }

  getCountries() {
    this.rest.getCountries().subscribe(res =>{
      this.countries=res;
      console("status code--->"+res.status)
    },
    err=>{
      console("status code--->"+err.status)
    })

  }
}

3 个答案:

答案 0 :(得分:0)

要获得完整的回复,您需要为响应添加额外的属性,observe就像这样 -

getCountries(): Observable<{}> {
    return this.http.get(this.apiUrl, {observe: 'response'}).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

有关详细信息,请参阅 -

答案 1 :(得分:0)

http.get方法的标题选项中添加观察:“响应”

getCountries(): Observable<{}> {
    return this.http.get(this.apiUrl,{observe : 'response'}).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }

并订阅get()方法以获取响应状态,就像您在首页中想要的那样

 getCountries() {
this.rest.getCountries().subscribe(
    res => {  this.countries=res;
  console("status code--->"+res.status)
},
err=>{
  console("status code--->"+err.status)
})
          },

答案 2 :(得分:0)

您可以使用Angular's interceptor在一个地方捕获所有错误并保持服务整洁。创建一个名为“错误拦截器”的新拦截器,并添加拦截方法:

  intercept(request, next) {
    // Handle response
    return next.handle(request).pipe(
      catchError(error => {
        //handle specific errors
        if (error.status === 401) {
          this.handle401();
        }

        //default case: print, log, toast, etc...
        return throwError(error.message || error);
      })
    );
  }