Welcome to part-13 of Angular Basics series. In this part , we will continue to learn to do HTTP requests in Angular.
The starting point is previous part can be taken from here.
We will convert our HTTP request from previous part to use services. Create a new file posts.service.ts inside the app folder.
We are moving the logic for the createPost and fetchPosts in it. But notice that in fetchPosts, we are not subscribing but only returning the result of the http request.
posts.service.ts
Back in app.component.ts file, we will remove the functions and add the call to services in it.
app.component.ts
Now, our app is working as earlier and we are able to get the posts.
localhost
Now, we will learn to clear or remove the posts from firebase. We are agin going to follow the service approach and create a deletePosts() in posts.service.ts file. It just use the http delete method to delete all data from our endpoint.
posts.service.ts
Now, we will add this to the onClearPosts() in app.component.ts file. After the delete confirmation, we are also making the loadedPosts array equal to empty.
app.component.ts
Now, from the localhost click on the Clear Posts button and all data will be deleted from firebase database also.
All deleted
Now, we will learn to do error handling in HTTP. We will emulate an error situation by giving the wrong url in posts.service.ts, in which i have just removed an alphabet.
posts.service.ts
Now, in app.component.html file, we will just show an error class with error. Also, notice that we are not showing the Loading if error is there.
app.component.html
Now, in app.component.ts file, we will show this error by passing it as a second argument after fetchPosts.
app.component.ts
Now, in localhost we will see this error with the error message.
Error with message
We will do one more change in our error handling. Now, we will add a button to clear the error in app.component.html file.
app.component.html
Back in app.component.ts file, we will add the function onHandleError to make the error null. We are also adding isFetching to false in both fetchPost, because we want to show No Posts available message.
app.component.ts
Now, our app is complete and error handling is working properly. This completes our post and you can find the code for the same in this github repo.