Angular Interceptors
Today, we’ll talk about simple and usefull interceptors.
Interceptors allow intercepting http requests. We can use different ways this. They are mostly used for error handling and token injecting. For example, if the token dies, the service returns an error with a status code of 401 or 403. We can capture that and send it back to the login page. But today we are working with fake api so we will do error handling part.
Let’s start with create a new angular project.And we importing HttpClient module.
We should create a service for api.We’ll write two function in service. The first is a GET request and will work fine. But the second will throw an error in response. We hope service will return 404 status code. Because the path specified is incorrect.
We should add two button in our component. And we’ll connect functions with service. Let’s see requests.
The first one seems ok but the second one didn’t work and users don’t know why. It’s time to create an interceptor.
ng g interceptor error-handler
Interceptors have a intercept function. We have to change this function using some rxjs.
After, we should import our interceptor to Module File. If we have more than one interceptor, we should care about ordering. Which interceptor is imported first will work in the same order.
Let’s check the page. Users will see this message and can know what happened.
If you want to see the code, click here.