Reputation: 6529
I'm creating a new app using angular and I want to set up some validations on route guards. For example my url is: localhost:4200/#/products
and if I want to navigate from the menu to other page of my app localhost:4200/#/invoice
I don't want that to be possible the navigation just manually modifying the url and typing invoice
instead of products
but only on menu click.
so this is my guard:
import { Injectable } from '@angular/core' ;
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
@Injectable()
export class AlwaysAuthGuard implements CanActivate {
canActivate() {
console.log('AlwaysAuthGuard');
return true;
}
}
and this is the routing service:
const appRoutes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', component: AppLoginComponent, data: { title: 'Login' }},
{ path: 'invoice', component: InvoiceComponent, canActivate: [AlwaysAuthGuard], data: { title: 'Invoice' }},
{ path: 'products', component: ProductsComponent, data: { title: 'Products' }},
{ path: 'logout', component: LogoutComponent, data: { title: 'Logout' }},
{ path: '**', component: NotFoundComponent, data: { title: 'Page Not Found' }}
];
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, { useHash : true });
So how can I add some validations on which I restrict the url modification and allow user to navigate to other pages only from navigation menu when is pressing on click.
Upvotes: 3
Views: 141
Reputation: 340
You can simply store some flag on menu click. example:
listen for click event on your menu link and then do the following:
localstorage.setItem('menu-clicked', 'true');
and then in your 'AlwaysAuthGuard' check if 'menu-clicked' is available in localstorage or not. example:
canActivate() {
// console.log('AlwaysAuthGuard');
if(localstorage.getItem('menu-clicked') == 'true'){
localstorage.removeItem('menu-clicked');
return true;
}
return false;
}
Upvotes: 1