Write Your Own Wrapper Over HTTP in Angular 2+ With Interceptor
Create your own HTTP service in your app
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
services in your
app/src directory. So, your directory will be:
In the services directory, create a file named
localStorage.service.ts and paste the below code:
In the above code, we have created our own local storage service which has methods like
remove() which will be used in any component.
Register the Local Storage Service in Our App
Let’s register this service in our
Create HTTP Service
Now, let's create our HTTP service. In this service, we will use our
LocalStorage service. To do this, create a file
http.service.ts in directory
src/app/services 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
app.module.ts, we have created a method
httpFactory() that uses the
providers 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.