Angular 2 Admin navigation/routes separate from Client side navigation/routes

前端 未结 2 1129
隐瞒了意图╮
隐瞒了意图╮ 2021-02-09 16:11

I know Angular 2 likes to use a single navigation to switch between pages. My issue is that the admin navigation is completely different than client facing navigation.

M

2条回答
  •  鱼传尺愫
    2021-02-09 17:09

    Here is a possible solution using basic routing and a guard to guard specific routes for admin priviledges only.

    In your routing config you will define the two main routes /user & /admin. You can then define child routes for those two main routes where they will extend off the parent route (example /admin/dashboard or /user/account)

    You can then regulate who has access to those routes based on a user role or whatever you decide. If you're storing user details in local storage, you can also store the users roles.

    Below is an untested example. I have comments inside the code blocks with a little explanation. I've also supplied a few links to write ups on routing and guards. Hopefully this helps a bit.

    Routing Config

    app.routing.ts

    import { NgModule } from '@angular/core';
    
    
    import { AdminComponent } from './admin.component';
    import { AdminDashboardComponent } from './admindashboard.component';
    import { UserAccountComponent } from './useraccount.component';
    import { UserComponent } from './user.component';
    
    import { RoleGuard } from './role.guard';
    
    const appRoutes: Routes = [
      {
        path: 'user',
        canActivateChild: [RoleGuard],        // <-- This guard will run before the router directs you to the route
        data: { roles : ['ROLE_USER'] },      // <-- Current Login in user must have role user.   You can access this array inside your guard.
        children: [
          {
            path: '',                    // <-- This should equal /user
            component: UserComponent,
            pathMatch: 'full'
          },
          {
            path: 'account',              // <-- This should equal /user/account
            component: UserAccountComponent,
            pathMatch: 'full'
          }
          // <-- The rest of your user routes
        ]
      },
      {
        path: 'admin',
        canActivateChild: [RoleGuard],         // <-- This guard will run before the router directs you to the route
        data: { roles : ['ROLE_ADMIN'] },      // <-- Current Login in user must have role admin
        children: [
          {
            path: '',
            redirectTo: '/admin/dashboard'   // <-- Redirects to dashboard route below
          },
          {
            path: 'dashboard',
            component: AdminDashboardComponent,
            pathMatch: 'full'
          }
          // <-- The rest of your admin routes
        ]
      }
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(appRoutes, { useHash: true })
      ],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}
    

    Role Guard

    role.guard.ts

    import { Injectable } from '@angular/core';
    import { Router, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    
    @Injectable()
    export class RoleGuard implements CanActivateChild {
    
      constructor(
        private router: Router
      ) {}
    
      canActivateChild(route: ActivatedRouteSnapshot, 
           state: RouterStateSnapshot): boolean {
    
        const userRoles: string[] = this.authService.getRoles();  // <--------- get the current user's roles
        const routeRoles: string[] = route.data['roles'];   // <------- Will get the roles arry you defined in your router config
    
        /*
          Now you can do your logic to determine if the user has the appropriate role.
          If they do return true
          Else use router to set a redirect route to /user url or whereever you feel like and return false;
        */
    
      }
    }
    

    Angular Router http://blog.angular-university.io/angular2-router/

    Angular Child Routes https://angular-2-training-book.rangle.io/handout/routing/child_routes.html

    Angular CanActivateChild https://angular.io/api/router/CanActivateChild

    More on routing https://blog.thoughtram.io/angular/2016/06/14/routing-in-angular-2-revisited.html

提交回复
热议问题