Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a dependency in HttpInterceptorFn in angular 17?

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

like image 655
GuilhermeMarques Avatar asked Dec 30 '25 23:12

GuilhermeMarques


1 Answers

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'));
    })
  );
};
like image 116
vbartalis Avatar answered Jan 05 '26 10:01

vbartalis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!