angularangular-routerangular-activatedroute

Angular route data empty after refresh or enter direct url in browser


I am facing issue with Angular routing while accessing the data property in the ActivatedRouteSnapshot instance.

The route data is available if I go by clicking the link button but if type url directly in the browser or refresh the page then route data is not available.

RouterModule routes:

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    component: DefaultLayoutComponent,
    children: [
      {
        path: 'usermanagement/userdetails/:username',
        canActivate: [AuthGuard],
        data: { parenturl: 'usermanagement/users', permissions: ["canView", "canAdd", "canEdit"] },
        component: UserDetailsComponent,
        canDeactivate: [CanDeactivateGuard]
      }
   ]
 },
];

Auth Guard:

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(
    private router: Router,
    private activeRoute: ActivatedRoute,
    private accountService: AccountService
  ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    var path = route.routeConfig?.path; // not found after refress
    var permissions = route.data["permissions"] // not found after refress
    return false;
  }
}

Solution

  • That is because you're using AuthGuard twice, in the parent and child route. Let's talk about what's happening when you are clicking the link or refreshing the page.