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:
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With