banjocode Angular Interceptors - Requests And Responses

Angular Interceptors - Requests And Responses

Angular interceptors are great when it comes to handling outgoing HTTP requests and incoming HTTP responses, this is a short guide on how to separate the two, and how to handle each type

3 min read

Interceptors

Interceptors are great to handle your HTTP events, they are very similar to middleware. You hand them an HTTP request or response, they modify it, and then pass it on. They are often used to add custom headers or tokens, log HTTP activity or format the body of the event.

There is a slight difference in how to handle request and responses with an interceptor, so without further ado:

Requests

Requests are probably the “easiest” to handle, as they are the standard. They are all the outgoing HTTP events you’ll send. The type is HttpRequest.

import { HttpInterceptor } from "@angular/common/http";
import { Injectable } from "@angular/core";

@Injectable()
export class ExampleInterceptor implements HttpInterceptor {
	intercept(
		request: HttpRequest<any>,
		next: HttpHandler
	): Observable<HttpEvent<any>> {
		// HttpRequests logic goes here
	}
}

All events that pass the intercept method will be requests. Logic regarding requests will be written here.

Responses

To handle responses, you need to use the HttpHandler to convert the HttpRequest to a stream of HttpEvents, some of them are most likely an HttpResponse. For this, we will use the next parameter.

import { HttpInterceptor } from "@angular/common/http";
import { Injectable } from "@angular/core";

@Injectable()
export class ExampleInterceptor implements HttpInterceptor {
	intercept(
		request: HttpRequest<any>,
		next: HttpHandler
	): Observable<HttpEvent<any>> {
		// HttpRequests logic goes here

		return next.handle(request).pipe(
			map((event: HttpEvent<any>) => {
				if (event instanceof HttpResponse) {
					// HttpResponse logic goes here
				}
			})
		);
	}
}

As you can see, we need to use RxJS to access the response, with the map operator. We look through each element to find an instance of the HttpResponse, and then modify it.