简体   繁体   English

如何以角度将拦截器范围限定到模块?

[英]How to scope interceptor to a module in angular?

Following is the interceptor in angular for replacing auth token.以下是用于替换身份验证令牌的 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);
  }
}

My app is structure like this:我的应用程序是这样的结构:

--- 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

Auth token will be available only after the login.身份验证令牌仅在登录后可用。

And I'm setting the interceptor for main module (ie provided in main module) (profile is where the user lands after login and sends requests based on received token)我正在为主模块设置拦截器(即在主模块中提供) (配置文件是用户登录后登陆并根据收到的令牌发送请求的地方)

But the issue here is that the interceptor is not getting called way before reaching the module.但这里的问题是拦截器在到达模块之前没有被调用。 So that when the profile component initialises and OnInit() I;m getting unauth response & when I check the console I can see that the Authorization header is undefined.因此,当配置文件组件初始化和OnInit()我收到未授权响应 & 当我检查控制台时,我可以看到授权标头未定义。

How can I solve this?我该如何解决这个问题?

NOTE I'm not providing it in root since this will spit out unauth error even before login.注意我没有在root提供它,因为即使在登录之前这也会吐出 unauth 错误。 So I'm providing the interceptor only inside the main.module.ts file.所以我只在main.module.ts文件中提供拦截器。

NOTE main module does not have any component with it.注意主模块没有任何组件。 It is used only to register profile module and items module.它仅用于注册配置文件模块和项目模块。

main module is getting loaded like this (from the root level):主模块是这样加载的(从根级别):

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

You can add condition like this if token is available then add token otherwise request send without token如果令牌可用,您可以添加这样的条件,然后添加令牌,否则请求不带令牌发送

    @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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM