The better way to write an API service in Angular 4

Saurabh Palatkar
Oct 28, 2017 · 2 min read

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:

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:

Base service

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

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:
https://medium.com/@spp020/44-quick-tips-to-fine-tune-angular-performance-9f5768f5d945

Thanks for reading.

Netscape

A community dedicated to those who use JavaScript every day.

Saurabh Palatkar

Written by

Sr. Lead at GlobalLogic, Nagpur. Just another developer. Loves creating awesomeness with JS and .NET. LinkedIn : https://www.linkedin.com/in/saurabh-p-15969767/

Netscape

Netscape

A community dedicated to those who use JavaScript every day.

Saurabh Palatkar

Written by

Sr. Lead at GlobalLogic, Nagpur. Just another developer. Loves creating awesomeness with JS and .NET. LinkedIn : https://www.linkedin.com/in/saurabh-p-15969767/

Netscape

Netscape

A community dedicated to those who use JavaScript every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store