如何在 Angular 17 中的 HttpInterceptorFn 中注入依赖?

问题描述 投票:0回答:1

这是我的拦截器,使用新的角度拦截方式,使用函数而不是类

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

但是在这个拦截器中,我想使用 Router 类来导航我的用户,但我无权访问要注入的构造函数,因为它是一个函数。

在 Angular 17 中使用 HttpInterceptorFn 进行拦截的新方式中使用依赖注入

angular dependency-injection interceptor angular-http-interceptors
1个回答
0
投票

只需简单地将其与

inject()
方法内联注入即可。

我修改了你的代码。在下面的示例中,

Router
和自定义
AuthenticationService
都被注入到方法中,然后它们可以在给定方法的范围内使用。

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'));
    })
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.