How to inject a dependency in HttpInterceptorFn in angular 17?

1.5k views Asked by At

Here is my interceptor using the new way of intercept of angular, using a function instead of a class

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  console.log('Intercepted');
  return next(req);
};

But in this interceptor I want to use the Router class to navigate my user, but I do not have access to my constructor to inject since it's a function.

Use Dependency injection in the new way of intercepting using HttpInterceptorFn in angular 17

1

There are 1 answers

2
vbartalis On

Just simply inject it inline with the inject() method.

I modified you're code. In the following example both the the Router and a custom AuthenticationService is injected into the method, then they can be used in the scope of the given method.

import { inject } from '@angular/core';
import { Router } from '@angular/router';

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const router = inject(Router);
  const authService = inject(AuthenticationService);
  console.log('Intercepted');
  return next(req).pipe(
    catchError((err) => {
      console.log(err);
      if (err.status === 401) {
        console.log('authInterceptor 401');
        authService.logout();
        router.navigate(['/auth/signout']);
      }
      return throwError(() => new Error('Unauthorized Exception'));
    })
  );
};