微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将参数传递给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);

原文地址:https://www.jb51.cc/angularjs/140926.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐