【问题标题】:catch api 404 response with Angular2 http使用 Angular2 http 捕获 api 404 响应
【发布时间】:2016-06-01 20:42:51
【问题描述】:

我有 api,如果失败,它会返回 400 或 404 错误。

当我运行 http.get 方法时,它不会在订阅时捕获错误并抛出错误。

Http.get(`api/path/here`).map(res => res.json()).subscribe(
            data => console.log(data),
            error => console.log(error)
        );

以下是我得到的错误

【问题讨论】:

  • 查看network 选项卡中的status code 和预览选项卡中的错误信息
  • @PardeepJain 状态码是 400,如果未找到用户对象,则 api 返回什么。

标签: http http-status-code-404 response angular


【解决方案1】:

您也可以使用catch 运算符

http.get(`api/path/here`)
    .map(res => res.json())
    .catch(
        err => {
          // handle errors
        })
    .subscribe(
        data => console.log(data)
    );

【讨论】:

  • “catch”是否比在订阅运算符本身上使用“onError”方法有任何好处?如果我只包含一个“onError”方法实现,是否有可能我的“map”运算符可能导致未捕获的异常?谢谢!
【解决方案2】:
.subscribe(res=>{
    this.data=res;
    console.log('bye');
 },
 (err)=>console.log(err),
 ()=>console.log("Done")
 );

试试这个方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 2018-09-13
    • 2016-12-14
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    相关资源
    最近更新 更多