Angular 2 HTTP get handling 404 error

13,691

Solution 1

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

Solution 2

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

Share:
13,691

Related videos on Youtube

Bas
Author by

Bas

PHP Vuejs developer

Updated on September 18, 2022

Comments

  • Bas
    Bas over 1 year

    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:

    enter image description here

    • Harry Ninh
      Harry Ninh
      Your given URL is https://jsonplaceholder.typicode.com/posts/6, and your URL in the code is https://jsonplaceholder.typicode.com/psts/6