使用 Angular2 http 捕获 api 404 响应

catch api 404 response with Angular2 http

我 api 如果失败,会出现 returns 400 或 404 错误。

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

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

以下是我得到的错误

.subscribe(res=>{
    this.data=res;
    console.log('bye');
 },
 (err)=>console.log(err),
 ()=>console.log("Done")
 );

试试这个方法。

您也可以使用 catch 运算符

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