Angular 2 HTTP handles 404 error

I have a service that was servicing empty json, but I am getting these errors. If I use https://jsonplaceholder.typicode.com/posts/6 then this is fine. How can I handle these errors correctly?

Services:

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

+5
source share
2 answers

You need to pass the second callback to the subscription method. This callback will be executed when an error occurs.

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

There is no problem in your code, URL gives 404

+4
source

Source: https://habr.com/ru/post/1258585/


All Articles