Part 15 Angular Tutorial | Angular Interceptor| Angular build | Deployment

preview_player
Показать описание
In Angular, an interceptor is a middleware that can intercept and modify HTTP requests and responses between the frontend and the backend server. Interceptors can be used for a variety of purposes, such as adding authentication headers, caching responses, or logging requests and responses.

To create an interceptor in Angular, you need to implement the HttpInterceptor interface, which provides two methods: intercept() and handleError(). The intercept() method is called for each HTTP request, and it can modify the request before it is sent to the backend server or intercept the response before it is returned to the frontend.

AuthInterceptor class implements the HttpInterceptor interface, and the intercept() method adds an authorization token to the request headers if the token is present in the localStorage. The clone() method is used to create a new HttpRequest object with the updated headers, and the handle() method is called on the next parameter to pass the modified request to the next interceptor or the backend server.

To use the interceptor in your Angular application, you need to provide it in the providers array of your AppModule:

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}

the HTTP_INTERCEPTORS token is used to register the AuthInterceptor class as an interceptor for all HTTP requests in the application. The multi: true option is used to allow multiple interceptors to be registered.
Рекомендации по теме
join shbcf.ru