gpt4 book ai didi

angular - 我怎样才能有条件地允许导航到用户

转载 作者:行者123 更新时间:2023-11-28 21:16:29 24 4
gpt4 key购买 nike

所以这是我的问题,我想在我的代码中测试这个 canActivate 函数。

我的AuthRoleGuardService.ts 文件:

export class AuthRoleGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authService.currentUserSubject.value;

if (Roles[currentUser.role] >= route.data.role) {
return true;
}

this.router.navigate(['/access-denied'], { queryParams: { redirect: state.url }, replaceUrl: true });
return false;
}
}

这是我到目前为止尝试过的:

  it('should allow navigation if user has minimum role', () => {});

it('should not allow navigation if user does not have minimum role', () => {
const role = 'DISPLAY';
const routerMock = jasmine.createSpyObj('Router', ['navigate']);
expect(roleGuard.canActivate(undefined, ({ url: 'users' } as any) as RouterStateSnapshot)).toBe(false);
expect(routerMock.navigate).toHaveBeenCalledWith(['access-denied']);
});

如何传递 Angular 色?

也许是一个好的解决方案:

  it('should not allow navigation if user does not have minimum role', fakeAsync(() => {
user.role = 'DISPLAY';

const route = new ActivatedRouteSnapshot();

route.data = { role: Roles.SHIFTLEAD };

expect(roleGuard.canActivate(route, mockStateSnapshot)).toBe(false);
expect(mockRouter.navigate).toHaveBeenCalledWith(['/access-denied'], {
queryParams: { redirect: undefined },
replaceUrl: true
});
}));

最佳答案

要测试守卫,你必须做这样的事情:

{ path : "", component : ComponentName, canActivate : [GuardName]}

编辑

案例一:

export class AuthRoleGuardService implements CanActivate {
test : number = 0 ;
constructor(private authService: AuthService, private router: Router) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

if (this.test != 0) {
return true;
}

this.router.navigate('/access-denied');
return false;
}
}

对于这种情况,用户将停留在他所在的页面,因为我无法访问目标页面

案例 2:

export class AuthRoleGuardService implements CanActivate {
test : number = 0 ;
constructor(private authService: AuthService, private router: Router) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

if (this.test == 0) {
return true;
}

this.router.navigate('/access-denied');
return false;
}
}

对于这种情况,用户将转到目标页面,因为 test 的值等于“0”

关于angular - 我怎样才能有条件地允许导航到用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57216358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com