In my Angular app has 3 types of users: admin, brewer (vendor) & end user. I want to prevent brewer from accessing admin routes, just as end users should be prevented from accessing admin routes and vendor route.
How I can achieve this through angular routing.
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{
path: 'home', component: HomeContentComponent,
},
{ path: 'auth', loadChildren: './modules/auth/auth.module#AuthModule' },
{
path: 'admin',
loadChildren: './modules/admin/admin.module#AdminModule',
canActivate: [AuthGuard],
},
{
path: 'vendor',
loadChildren: './modules/vendor/vendor.module#VendoreModule',
canActivate: [AuthGuard],
},
{
path: 'user',
loadChildren: './modules/user/user.module#UserModule',
canActivate: [AuthGuard],
}
]
Auth Guard :
import { Injectable } from "@angular/core";
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router,
CanDeactivate,
} from "@angular/router";
import { Observable } from "rxjs";
import { AuthService } from "../services/firebase/auth.service";
@Injectable({ providedIn: "root" })
export class AuthGuard implements CanActivate {
constructor(public authService: AuthService, public router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
// Guard for userRole is login or not
// var Role=localStorage.getItem('role')
let user = localStorage.getItem('toke');
if (!user) {
this.router.navigate(["/auth/login"]);
return true;
}
return true;
}
}
I have auth guard like this how I can modify it to achieve desired functionality.
It would be greatly appreciated if anyone could help.
canActivateproperty of a route, you can pass in multiple guards. Create the guards that you need and put them in the array, next to theAuthGuard. If you have already implemented the guards for vendor and normal user and they don't work as you expect them to, then include those in the body of your question.