2

I am on Angular 8. I have routing module setup as below.

{ path: '', redirectTo: 'ads', pathMatch: 'full' },
{
  path: 'ads',
  loadChildren: () => import('./ads/ads.module').then(m => m.AdsModule)
},
{
  path: 'user',
  loadChildren: () => import('./user/user.module').then(m => m.UserModule)
}

I have a seperate AdsModule in which some child has authGuard and some do not as below:

{ path: '', component: AdsComponent, children: [
    { path: '', redirectTo: 'all', pathMatch: 'full' },
    { path: 'all', component: AdsListComponent },
    { path: 'myads', component: MyAdsComponent, canActivate: [AuthguardService]},
    { path: 'postnewad', component: PostAdComponent, canActivate: [AuthguardService]},
    { path: 'edit', component: PostAdComponent, canActivate: [AuthguardService]},
    { path: ':id', component: AdDetailsComponent },

  ]},

I have an HttpInterceptor implemented which triggers a logout function for the user if the accessToken is expired. The logout function is setup as below:

logoutUser() {
    const currentRouteConfig = this.router.config.find((f) => {
      let s = this.router.url.substr(1);
      const n = s.indexOf('/');
      s = s.substring(0, n !== -1 ? n : s.length);
      if (f.path.includes(s)) {
        return true;
      }
    });
    if (currentRouteConfig.canActivate) {
      console.log(currentRouteConfig);
      this.router.navigate(['user']);
    }
    this.removeLoggedInUser();
  }

The above function was working all fine until I did not have lazy loading and all routes along with children were known at the root. However, after I implemented lazy loading, the above function does not work (obviously) because the currentRouteConfig property never has the canActivate attribute to. I checked and found that the lazy loading routes are not available to the router in the config, its only available under _loadedConfig which is a locked property and cannot be accessed.

I am having a hard time figuring out what needs to be done in order to get it to work. Some forums suggest I do it using ComponentFactoryResolver but the solution is always implemented in a component. I need to do this at a service level so that it can be available for multiple components.

Please help me tackle this.

Thanks

Saad Momin
  • 97
  • 1
  • 6

0 Answers0