Angular – Intercepting Http Calls

Angular allows you to intercept web requests and responses through HttpInterceptor implementations.

In this tutorial we will demonstrate how to create and use an http interceptor implementation in order to intercept http requests for adding a dummy authentication header and setting a custom read timeout parameter then we will demonstrate intercepting the response for handling http 401 error.

In order to create a custom http interceptor you need to implement HttpInterceptor interface.

@Injectable()
export class SessionInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
	……
	……
  }
}

Then add your HttpInterceptor implementation into providers inside your app.module.ts file.

{
   provide: HTTP_INTERCEPTORS,
   useClass: SessionInterceptor,
   multi: true
}

Intercepting and Adding Http Header to the Request

Inside the intercept method, we are adding headers to the request then setting 5000 as timeout parameter then returning the resultant request object.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
	let result: Observable<HttpEvent<any>> = next.handle(this.addHeaders(request));

	  result = result.pipe(
		timeout(5000)
	  );

	return result;
}

Altering the request is done through creating a clone of the request by setting the headers property.

private addHeaders(request: HttpRequest<any>): HttpRequest<any> {
	const alteredRequest = request.clone({
	  setHeaders: {
		Authorization: `Dummy-Auth ${this.getDummyToken()}`
		}
	});
	return alteredRequest;
}

Intercepting the Response

If we want to intercept the response for error handling we can pipe a catchError to the httpEvent that’s returned from next.handle(request) call. We must rethrow the error not to break the exception firing flow. If what you want is just handling the successfull response events then you can use a map operator instead.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
	return next.handle(request).pipe(
	  catchError((error: HttpErrorResponse) => {
		if (error.status === 401)) {
		  // handle properly
		}
		return throwError(error);
	}));
}

Leave a comment