最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 HTTP get handling 404 error - Stack Overflow

programmeradmin0浏览0评论

I have a service which served an empty json, but i am getting these errors. If i use then its ok. How can i handle these errors in the correct way?

Service:

constructor( private http:Http ) { }

fetchData(){
  return this.http.get('')
      .map(
          (res) => res.json()
      )
      .subscribe(
        (data) => console.log(data)
  );
}

Error:

I have a service which served an empty json, but i am getting these errors. If i use https://jsonplaceholder.typicode.com/posts/6 then its ok. How can i handle these errors in the correct way?

Service:

constructor( private http:Http ) { }

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

Error:

Share Improve this question edited Oct 21, 2016 at 9:32 Xameer 31.2k27 gold badges146 silver badges229 bronze badges asked Oct 21, 2016 at 6:55 BasBas 2,4006 gold badges34 silver badges70 bronze badges 4
  • And why are you omitting the o? – Harry Ninh Commented Oct 21, 2016 at 6:57
  • @HarryNinh what do you mean? – Bas Commented Oct 21, 2016 at 7:04
  • 1 Your given URL is https://jsonplaceholder.typicode.com/posts/6, and your URL in the code is https://jsonplaceholder.typicode.com/psts/6 – Harry Ninh Commented Oct 21, 2016 at 7:06
  • This I have done to create an error – Bas Commented Oct 21, 2016 at 7:11
Add a comment  | 

2 Answers 2

Reset to default 10

You need to pass a second callback to the subscribe method. This callback will execute when there is an error.

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)
  );
}

There is no problem in your code, the URL itself is giving a 404

发布评论

评论列表(0)

  1. 暂无评论