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
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'));
})
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With