如何获取angular 2路由器错误的http状态代码

时间:2016-11-03 16:13:55

标签: angular angular2-router

我的组件模板url指向生成响应html的服务器,当出现问题时,它可能会返回不同的http错误状态代码(401,403等)。 如果在加载路由时发生错误,我希望得到错误状态。 使用router.events.subscribe并检查NavigationError不会仅为某些文本提供http错误状态 - “无法加载url / to / my / template”。 知道如何获得响应http状态代码吗?

1 个答案:

答案 0 :(得分:0)

此函数以URL作为参数发出HTTP请求。

get_http_response(url) {
this._http.get(url)      /*this make http request to server*/
.map((response: Response) => {
  response.json();
  this.responseStatus = response.status; /* local variable to restore status code. */
}) /*this get response back and map it*/
// ...errors if any
.catch((error: any) => Observable.throw(error.json().error || 'Server error')
)
.subscribe(
  resdata => {
    this.getdata = resdata; /*local variable to store data. */
    console.log("fetched data =>" +this.getdata);
    console.log("status code =>" + this.responseStatus);
  }
);

}

如果您在下面的帖子中收到任何错误评论,我认为它会解决您的问题。

谢谢。