I want to check all my http responses from one place. For example authentication status. If response says user not authenticated any more I wanna redirect or something else. Is there any way to do that.
What Are Http Interceptors And How to Use Them In Angular? Use cases where we can make use of Interceptors in Angular. We have faced multiple scenarios where we might want to globally capture or change every request or response, like append a user’s token or handle errors from the response and we can achieve this using Http Interceptor.
Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient. They can handle both HttpRequest as well as HttpResponse. By intercepting the Http request, we can modify or change the value of the request, and by intercepting the response, we can do some predefined actions on a particular status code or message.
The $http service of AngularJS allows us to communicate with a backend and make HTTP requests. There are cases where we want to capture every request and manipulate it before sending it to the server. Other times we would like to capture the response and process it before completing the call.
Interceptors can be used to format JSON responses, retry the failed request calls a fixed number of times or log analytics of each request & response which can be helpful in monitoring. These are the use cases of Interceptors apart from the ones that I explained — Adding Http Headers and Global Error Handling.
Here we go
Create a Service like that
export const JWT_RESPONSE_HEADER = 'X-Auth-Token';
@Injectable()
export class AuthHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
const request = super.request(url, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
const request = super.get(url, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
const request = super.post(url, body, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
const request = super.put(url, body, this.appendAuthHeader(options));
request.subscribe(this.saveToken);
return request;
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
const request = super.delete(url, this.appendAuthHeader(options));
request.map(this.saveToken);
return request;
}
private appendAuthHeader(options?: RequestOptionsArgs): RequestOptionsArgs {
let mergedOptions: RequestOptionsArgs;
if (!options) {
mergedOptions = { headers: new Headers() };
} else {
mergedOptions = options;
}
const token = localStorage.getItem(JWT_RESPONSE_HEADER);
const isTokenSet = mergedOptions.headers.has('Authorization');
if (token && !isTokenSet) mergedOptions.headers.append('Authorization', `Bearer ${token}`);
return mergedOptions;
}
private saveToken(res: Response): void {
const token = res.headers.get(JWT_RESPONSE_HEADER);
if (token) localStorage.setItem(JWT_RESPONSE_HEADER, token);
}
}
And include it in you app.module.ts like this
@NgModule({
imports: [
BrowserModule,
ContentModule,
routing,
HttpModule
],
declarations: [
AppComponent,
LoginComponent
],
providers: [
appRoutingProviders,
LoginService,
{
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new AuthHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
you dont have to make any changes to your other service witch use http
https://github.com/mtinner/CAS-FEE_Project2/blob/develop/src/frontend/components/common/authentication/auth-http.service.ts
https://github.com/mtinner/CAS-FEE_Project2/blob/ebab26fb8a8463cf9f65c3bc9e4d806d665bec7e/src/frontend/components/app.module.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With