It’s more than a year now since I’ve been coding Angular 2. Each day I learned something new. Angular is a full UI framework which promotes many best practices and coupled with Typescript makes it the perfect choice for the large-scale and easily scalable applications.
During my continuous learning process, I created an organized and well-structured Angular API service which I refactored with each iteration. So let’s see what exactly I built. You can download complete code here.
The Custom HTTP provider:
First, create a custom HTTP service ( http.service.ts) extending Angular’s inbuilt http service so that I can control all the http calls going through the application at one place and can do some pre and post processing at one go.
Ok, in above HttpService as you can see I am processing all the API requests inside request() method before making the actual API call. Also, this service gives me the ability to handle all API server errors at one place (catchError()). I am also using something called injector to inject different services on the fly. This injector is the part of my AppModule and you can include it in AppModule like this:
Next, we will create base.service.ts which will have different methods corresponding to different http verb methods:
As you can see, instead of using Angular’s inbuilt Http service I am using my custom HttpService which we just created above. My server API always sends a response in the specific format (ServerResponse interface), which makes it easy for me to process and parse errors in case of any server errors.
Server Response Interface
Error Handler Service
Login API Call
Finally, this is how we can consume our API service to make a login API call. We will be consuming BaseService which we created to make an API call.
So this is how we can write API calls in a better and cleaner way. Hope you enjoyed reading.
If you are looking for ways to improve your Angular app performance then take a look at following article for quick tips:
Thanks for reading.