3

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.

5
  • 2
    In the canActivate property of a route, you can pass in multiple guards. Create the guards that you need and put them in the array, next to the AuthGuard. 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. Commented Apr 14, 2022 at 10:11
  • 1
    Does this answer your question? Pass parameter into route guard Commented Apr 14, 2022 at 10:20
  • 2
    Follow this geekstrick.com/… Commented Apr 14, 2022 at 10:35
  • Hey @Abhishek you're correct but marked solution seems easy to me that's why I choose that. Thanks for helping me. Commented Apr 15, 2022 at 4:49
  • @konowo7640 there's easy and there's right. Picking easy will not get you far. Commented Mar 15, 2023 at 10:19

2 Answers 2

2

I have achieved this by using logic,

You can use logic like in your app.component.ts

import { Router, NavigationEnd } from '@angular/router';
    
export class AppComponent implements OnInit {
      constructor(
        private router: Router,
      ) {
        this.router.events.subscribe((ev) => {
          if (ev instanceof NavigationEnd) {
    
            const user = localStorage.getItem("Id");
            const Role = localStorage.getItem('UserRole')
            if (user && Role && Role === 'User' && ev.url.includes('/admin)) {
                this.router.navigate(['user/home']);
          }
        }
      }

Similarly for your all roles you can define if condition and can redirect on their main route lets if user then user's default page, if super admin then it might be admin/dashboard anything like this.

Second way:

Another way to achieve this is to use ngx-permissions using which you can control your route based on role.

attaching stackblitz demo for more clarification.

Official doc

NPM Package

Sign up to request clarification or add additional context in comments.

1 Comment

This is NOT the proper way to do it (and should not be the accepted answer). The proper way is to use Guards. That's exactly what they're there for.
0

you can do it with multiple if else condition

const Role = localStorage.getItem('role')
if(Role != "admin"){
    this.router.navigate(["/auth/login"]);
}

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.