Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 HTTP get handling 404 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:

enter image description here

like image 784
Bas Avatar asked Oct 21 '16 06:10

Bas


People also ask

How to handle errors when HTTP fails in Angular?

When the error occurs in the HTTP Request it is intercepted and invokes the catchError . Inside the catchError you can handle the error and then use throwError to throw it to the service. We then register the Interceptor in the Providers array of the root module using the injection token HTTP_INTERCEPTORS .

How to catch error in Http request in Angular?

The basic way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError and catchError. The HTTP request is made, and it returns the data with a response if anything wrong happens then it returns an error object with an error status code.

What is HttpErrorResponse in Angular?

HttpErrorResponselink A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.


2 Answers

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)
  );
}
like image 125
Bazinga Avatar answered Oct 01 '22 00:10

Bazinga


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

like image 34
xameeramir Avatar answered Sep 30 '22 23:09

xameeramir