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;
}
}
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.
UserDetails
page only the second one will be invoked and there will be data availableAuthGuard
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.