'How to pass parameter to guard?
I have project-based angular 12.
I need to secure a route based on a parameter which is colled token:
export const authenticationRoutes = [
{
path: 'reset-password/token/:token',
component: ResetPasswordShellComponent,
canActivate: [ResetPasswordGuard]
}
];
ResetPasswordGuard is a guard that makes calls to web service and should send token value which is part of the path:
path: 'reset-password/token/:token'
My question is there any way to pass token value from the path to guard(ResetPasswordGuard) so it will be sent to the web service?
Solution 1:[1]
When we implement the interface CanActiavte on ResetPasswordGuard, the function canActivate takes 2 parameters, first of which is ActivatedRouteSnapshot...
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
// your logic goes here
console.log('[ResetPasswordGuard]', next.params); // <-- This should print {token: 'somevalue'}
....
....
}
So one can easily read path parameters from it using...
const tokenInPath = next.params.token || ''
Using an ActivatedRouteSnapshot one has access to the whole data in the URL. ActivatedRouteSnapshot also provides Observable interfaces for reading/receiving intended information(path params, query params etc...).
WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nalin Ranjan |
