将参数传递给Guard Angular 2

时间:2016-12-27 18:13:02

标签: angular routing

我有一个我使用Authentication Guard设置的应用,以确保用户无法访问该应用,除非他们已登录,如此

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>

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

2 个答案:

答案 0 :(得分:9)

我找到了解决方案

    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, 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', canActivate: [IsInRoleGuard], component: DashboardComponent, data: {
                    roles: [
                        'admin',
                        'super-admin'
                    ]
                }
            }
        ]
    }
];

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

答案 1 :(得分:5)

Guard只是一个实现CanActivate或CanDeactivate的类。但是没有什么能阻止你注入一个能让你回到用户角色的服务(或价值)。例如,

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

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
          if (!this.user.isAdmin()) return false;
          ...

    }
}