将参数传递给Guard Angular 2

我有一个应用程序,我已使用身份验证防护设置,以确保用户无法访问该应用程序,除非他们已登录,如此
import { Injectable } from '@angular/core';
import {
    CanActivate,Router,ActivatedRouteSnapshot,RouterStateSnapshot,CanActivateChild } from '@angular/router';
import { AuthContext } from './auth-context.service';

@Injectable()
export class AuthGuard implements CanActivate {
        constructor(private router: Router,private authContext: AuthContext) { }

    canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
        // Check to see if a user has a valid JWT
        if (this.authContext.userInfo !== undefined && this.authContext.userInfo.isAuthenticated) {
            // If they do,return true and allow the user to load the home component
            return true;
        }

        // If not,they redirect them to the login page
        this.router.navigate(['/login']);
        return false;
    }

    canActivateChild(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
        return this.canActivate(route,state);
    }
}

我想为授权添加一个警卫,以检查用户是否处于某个角色.目前,我正在隐藏基于此角色的导航链接.

<div *ngIf="userInRole('Admin')">
             This is secret stuff
 </div>

但是如果用户知道路线,他们只需将其插入网址即可.如何将我的“userInRole()”类型功能添加到Guard?我必须传递角色名称并执行签入代码.卫兵支持参数吗?

我找到了解决方
import { Injectable } from '@angular/core';
    import { CanActivate,RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { AuthService } from './service/auth.service';

    @Injectable()
    export class IsInRoleGuard implements CanActivate {
        constructor(
            private _authService: AuthService
        ) { }

        async canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
            const userRole = this._authService.getRole(); // Get role from service
            if (next.data['roles'].indexOf(userRole) !== -1) {
                return true;
            }
            return false;
        }
    }

并在您的router-config

import { Routes,RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import { RootComponent } from './root/root.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { IsInRoleGuard } from '../../guards/is-in-role.guard';

const routes: Routes = [
    {
        path: '',component: RootComponent,children: [
            {
                path: '',pathMatch: 'full',component: DashboardComponent,data: {
                    roles: [
                        'admin','super-admin'
                    ]
                }
            }
        ]
    }
];

export const RouterConfig: ModuleWithProviders = RouterModule.forChild(routes);

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...