0

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

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.