简体   繁体   English

基于 Angular 6 角色的根 url 路由

[英]Angular 6 role based routing on root url

I'm trying to implement role based routing for my root url.我正在尝试为我的根 url 实现基于角色的路由。 For example, when user logged in, I can redirect him to User's dashboard page from login.component.例如,当用户登录时,我可以将他从 login.component 重定向到用户的仪表板页面。 Same applied for admin, also redirect to admin dashboard page through login.同样适用于管理员,也通过登录重定向到管理员仪表板页面。 But how to redirect to specific dashboard using role if user opens root url?但是,如果用户打开根 url,如何使用角色重定向到特定仪表板?

Currently my root route points to dashboard component which parse roles and redirect to desired dashboard page, user or admin.目前我的根路由指向仪表板组件,它解析角色并重定向到所需的仪表板页面、用户或管理员。 Is there a way to eliminate dashboard component?有没有办法消除仪表板组件?

AppRouting.ts AppRouting.ts

export const AppRoutes: Routes = [

    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full'
    },  

{
        path: '',
        component: AdminLayoutComponent,
        canActivate: [AuthGuard],
        canLoad: [AuthGuard],
        children: [
            {
                path: 'dashboard',
                loadChildren: './dashboard/dashboard.module#DashboardModule'
            },  

DashboardRouting.ts DashboardRouting.ts

export const DashboardRoutes: Routes = [

    {
        path: '',
        component: DashboardRedirectComponent,
    },

Test DashboardRedirect Component:测试 DashboardRedirect 组件:

export class DashboardRedirectComponent implements OnInit, AfterViewInit {

    constructor(private auth: AuthenticationService, private router: Router) {

        let currentUser = JSON.parse(localStorage.getItem('currentUser'));

        if (this.auth.loggedIn()) {

            if (currentUser['role'] == 'User') {
                this.router.navigate(['/dashboard/user']);
            }

            if (currentUser['role'] == 'Admin') {
                this.router.navigate(['/dashboard/admin']);
            }
        }
    }

I've tried to implement that using guards and even resolver but it didn't work out.我尝试使用警卫甚至解析器来实现它,但没有成功。 When I open root page of my app, it navigates to dashboard and after few seconds navigates to corresponding dashboard page, but I'd like to navigate user right away and without extra component for this.当我打开我的应用程序的根页面时,它导航到仪表板,几秒钟后导航到相应的仪表板页面,但我想立即导航用户而不需要额外的组件。 Any suggestion ?有什么建议吗?

If you want to skip the current routing you need to return false from your guard.如果你想跳过当前的路由,你需要从你的守卫返回 false。 In your role based redirect, first check if the user is actually routing to your base component /dashboard and not to a specific route /dashboard/admin otherwise you would intercept the role based routing.在基于角色的重定向中,首先检查用户是否实际路由到您的基本组件/dashboard而不是特定路由/dashboard/admin否则您将拦截基于角色的路由。 Then check the roles and when you want to redirect return false to skip the actual routing.然后检查角色以及何时要重定向返回 false 以跳过实际路由。

Eg:例如:

 canActivate (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    const roles = this.permissionsService.getPermissions();

    switch (true) {
      case state.url !== '/home': {
        return true;
      }
      case !!roles['admin']: {
        this.router.navigate(['home', 'admin']);
        return false;
      }
      case !!roles['user']: {
        this.router.navigate(['home', 'user']);
        return false;
      }
      default: return true;
    }

  }

You need to create a Guard name as RedirectGuard as follows:您需要创建一个 Guard 名称作为RedirectGuard ,如下所示:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class RedirectGuard implements CanActivate {
 let currentUser = null;
 let auth = null;

    constructor(private authenticationService: AuthenticationService) {
      this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
      this.auth =  authenticationService;
     }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      //Your redirection logic goes here

      if (this.auth.loggedIn()) {

        if (currentUser['role'] == 'User') {
            this.router.navigate(['/dashboard/user']);
        }

        if (currentUser['role'] == 'Admin') {
            this.router.navigate(['/dashboard/admin']);
        }
    }
   return false;

    }
}

Use RedirectGuard Inside AppRouting.ts as follows:AppRouting.ts 中使用RedirectGuard如下:

path: '',
        component: AdminLayoutComponent,
        canActivate: [RedirectGuard],
        canLoad: [AuthGuard],
        children: [
            {
                path: 'dashboard',
                loadChildren: './dashboard/dashboard.module#DashboardModule'
            }, 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM