What is interceptor in angular?
This is important for us as developer know about interceptor
so In Angular, an interceptor is a mechanism for handling or transforming HTTP requests and responses globally before they reach the components. It allows you to pre-process or post-process requests and responses. It is commonly used for tasks such as adding headers, handling errors, transforming data, etc.
why I say that an interceptor is important ? because they provide a way to handle HTTP requests and responses in a centralized and reusable manner, rather than having to write the same code in multiple places. This can improve the maintainability, readability, and testability of your code. Additionally, using interceptors can simplify common tasks such as adding headers or handling errors, reducing the amount of repetitive code and making it easier to make global changes.
Now Im gonna create the simple interceptor for handle error 401 response service
the first step we should create the interceptor, we can use commandline to generate interceptor
ng g interceptor error
Angular will create the file error.interceptor.ts
like this
and will automaticly create the code interceptor like this
and we can add some code to detect error server
we will navigate the user is not login to login or to 401 page
but we already create the interceptor file we must import this to app.module.ts
And this will direct to 401 page
Top comments (0)