首页 > 解决方案 > 如何以角度将拦截器范围限定为模块?

问题描述

以下是用于替换身份验证令牌的 Angular 拦截器。

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(
  ) {
  }

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const token: string = localStorage.get('token');
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });
    return next.handle(request);
  }
}

我的应用程序是这样的结构:

--- app
   ---login // this is a routed module
   ---signup // this is a routed module
   ---main // this is a routed module
           ---profile // this is a routed child module
           ---items // this is a routed child module

身份验证令牌仅在登录后可用。

我正在为主模块设置拦截器(即在主模块中提供)(配置文件是用户登录后登陆并根据接收到的令牌发送请求的位置)

但这里的问题是拦截器在到达模块之前没有被调用。因此,当配置文件组件初始化并且OnInit()我得到未验证响应时,当我检查控制台时,我可以看到授权标头未定义。

我该如何解决这个问题?

注意我没有提供它,root因为这会在登录之前吐出 unauth 错误。所以我只在main.module.ts文件中提供拦截器。

注意主模块没有任何组件。它仅用于注册配置文件模块和项目模块。

主模块是这样加载的(从根级别):

  {
    path: '',
    loadChildren: () => import('./main/main.module').then((m) => m.MainModule),
    canActivate: [AuthGuard],
  },

标签: angular

解决方案


如果令牌可用,您可以添加这样的条件,然后添加令牌,否则请求不带令牌发送

    @Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(
  ) {
  }

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const token: string = localStorage.get('token');

     if(token && token.length){

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

     }
    return next.handle(request);
  }
}

推荐阅读