- Create this class
@Injectable({
providedIn: 'root'
})
export class GlobalHttpInterceptorService {
constructor() {
this.initInterceptor();
}
private initInterceptor(): void {
// Store the original methods of XMLHttpRequest
const originalOpen = XMLHttpRequest.prototype.open;
const originalSend = XMLHttpRequest.prototype.send;
// Intercept requests before they are sent
XMLHttpRequest.prototype.open = function (method: string, url: string, async?: boolean, user?: string | null, password?: string | null) {
// Add your logic here to modify the request, add headers, etc.
// For example, you can check if a bearer token exists in local storage and add it to the headers
const bearerToken = localStorage.getItem('your_token_key');
if (bearerToken) {
this.setRequestHeader('Authorization', `Bearer ${bearerToken}`);
}
originalOpen.apply(this, arguments);
};
// Intercept the response
XMLHttpRequest.prototype.send = function (data?: any) {
const self = this;
const originalOnReadyStateChange = this.onreadystatechange;
this.onreadystatechange = function () {
if (self.readyState === 4) {
// Add your logic here to handle the response if needed
// Call the original onreadystatechange
originalOnReadyStateChange && originalOnReadyStateChange.apply(this, arguments);
}
};
originalSend.apply(this, arguments);
};
}
}
- Register it in the app.module.ts
@NgModule({
imports: [BrowserModule, HttpClientModule],
providers: [
GlobalHttpInterceptorService,
// If you have other interceptors, you can add them to the HTTP_INTERCEPTORS array as well.
// {
// provide: HTTP_INTERCEPTORS,
// useClass: YourOtherInterceptor,
// multi: true
// }
],
bootstrap: [YourAppComponent]
})
export class AppModule {}
- Create an HttpInterceptor class:
First, create a new Angular service that implements the HttpInterceptor
interface. This interceptor will add the bearer token to the headers of each outgoing HTTP request.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the bearer token from storage (you may replace 'your_token_key' with your actual token key)
const bearerToken = localStorage.getItem('your_token_key');
// Clone the request and add the bearer token to the headers
if (bearerToken) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${bearerToken}`
}
});
}
// Continue to the next interceptor or send the modified request directly
return next.handle(request);
}
}
- Provide the Interceptor in your AppModule:
In your app's module (usually app.module.ts
), provide the interceptor by adding it to the HTTP_INTERCEPTORS
multi-provider. This will make it available globally throughout your application.
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor'; // Import the AuthInterceptor class you created
@NgModule({
imports: [HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
export class AppModule {}
- Store the bearer token:
Before making any HTTP requests, make sure to store the bearer token in a place accessible to the interceptor. You can store the token in LocalStorage, SessionStorage, or a service that holds authentication-related data. For this example, I used LocalStorage.
When the user logs in or receives the token from the server, store it like this:
// Assuming you have the token after successful authentication
const token = 'your_bearer_token';
localStorage.setItem('your_token_key', token);