Developerzzz
Developerzzz

Reputation: 1126

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

Upvotes: 0

Views: 1813

Answers (1)

matikowy
matikowy

Reputation: 170

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.

  • clicking the link - the first guard for the parent route has been already invoked, when you are clicking the link to you UserDetails page only the second one will be invoked and there will be data available
  • refreshing the page - the first and second guards will be invoked one by one. The first one doesn't have the data property available so there is no data. You don't have to use the AuthGuard twice as it will be invoked for the child route, because it is in the parent route. Simply move the data property to the parent and remove it from the child or just remove it from the parent.

Upvotes: 2

Related Questions