Do you need control over all http requests of your app at once? Use an Angular http interceptor for incoming or outgoing http! In this post we will add a api-key header to all outgoing http requests and navigate to the login page for all 401 responses.

We are using plain Angular by implementing the HttpInterceptor interface (documentation here).

We are going to extend a simple application created in a previous post on ng-apimock. This application has already an http call with appropriate mocks. The complete code for the angular http interceptor is found on github here.

Outgoing http

Suppose our app is calling api’s via an api portal, for example an azure api portal. To gain access to the api we have to send our subscription key in a custom header. Here we implement HttpInterceptor so every outgoing http request gets the appropriate headers.

@Injectable()
export class SubscriptionKeyInterceptor implements HttpInterceptor {

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const newHeaders = request.headers
            .set('Az-Subscription-Key', environment.subscriptionKey)
            .set('Az-Trace', String('true'));

        return next.handle(request.clone({ headers: newHeaders }));
    }
}

Note that we clone the request and append the headers onto the existing headers. If we now run the app we see the headers being set.

Screenshot 2020 01 03 at 14.45.07 - ANGULAR HTTP INTERCEPTOR

Incoming http

Let’s say the api returns specific information for the currently logged in user. This means the api returns a 401 for other users. We should navigate the user too the login page on such an event.

@Injectable()
export class AuthenticateHttpInterceptor implements HttpInterceptor {

    constructor(
        private router: Router
    ) { }

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

        return next.handle(request).pipe(
            catchError((error: HttpErrorResponse) => {
                if (error.status === 401) {
                    this.router.navigate(['/login']);

                    return EMPTY;
                }

                return throwError(error);
            })
        );
    }

Here we see the same setup as for outgoing http requests. But the mutation is not on the request but instead on the handled request here. The 401 error is caught and we navigate to the login page. For other errors we propagate the error. Now test your interceptor.

Screenshot 2020 01 03 at 14.55.48 - ANGULAR HTTP INTERCEPTOR

Hopefully you can now implement your own Angular http interceptor and control the http flow. Happy intercepting!