Write Your Own Wrapper Over HTTP in Angular 2+ With Interceptor

Create your own HTTP service in your app

Shubham Verma
Jan 17 · 2 min read
Photo by Annie Spratt on Unsplash

In this article, we are going to create our own HTTP service, which will be very easy, reusable, and you’ll need to write less code in your app.

Also in this article, we will create our own local storage service that will be used in our own HTTP service. This service will intercept our request and save the data (token) in local storage too.

So, let’s start…


Create Local Storage Service

We need to create a local storage service first, To do this, create a folder named in your directory. So, your directory will be: .

In the services directory, create a file named and paste the below code:

In the above code, we have created our own local storage service which has methods like , , , and which will be used in any component.


Register the Local Storage Service in Our App

Let’s register this service in our file.

:


Create HTTP Service

Now, let's create our HTTP service. In this service, we will use our service. To do this, create a file in directory and paste the below code:

:

In the above code, we have created our own HTTP service. We have also created an interceptor that will be used for every HTTP request/response.

In the above code, we have created our own method (GET, POST, PUT, DELETE ) just like the HTTP method. Now we will call our own method in our component.


Register HttpService in app.module.ts

In the file , we have created a method that uses the array as above.


Using Our Own HTTP Service With Much Less Code

Let’s use this service in our existing component:

It's done, we have created our own HTTP service and we can use this by simply importing our components.

Thanks for reading.

Better Programming

Advice for programmers.

Shubham Verma

Written by

A full-stack developer, In my free time, I write blogs and play guitar. I am both driven and self-motivated.

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

Why Do Incompetent Managers Get Promoted?

978

More from Better Programming

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