javascript – Angular 2 HTTP得到处理404错误

我有一个服务空服务json,但我收到这些错误.如果我使用https://jsonplaceholder.typicode.com/posts/6然后它的确定.如何以正确的方式处理这些错误?

服务:

constructor( private http:Http ) { }

fetchData(){
  return this.http.get('https://jsonplaceholder.typicode.com/psts/6')
      .map(
          (res) => res.json()
      )
      .subscribe(
        (data) => console.log(data)
  );
}

错误:

enter image description here

最佳答案
您需要将第二个回调传递给subscribe方法.当出现错误时,将执行此回调.

function handleError(error) {
  console.log(error)
}

fetchData(){
  return this.http.get('https://jsonplaceholder.typicode.com/psts/6')
      .map(
          (res) => res.json()
      )
      .subscribe(
        (data) => console.log(data),(error) => handleError(error)
  );
}

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小