具有身份验证保护和规则的角路由

问题描述 投票:0回答:1

实际上我在我的authentication-guard.service.ts中有此代码

@Injectable({
  providedIn: AuthenticationModule
})
export class AuthenticationGuardService implements OnDestroy {
  private userSubscription: Subscription;
  private currentUser: User;

  constructor(private router: Router, private loginSelector: LoginSelector) {
    this.userSubscription = this.loginSelector
      .getUser()
      .subscribe(user => (this.currentUser = user));
  }

  ngOnDestroy() {
    this.userSubscription.unsubscribe();
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (!this.currentUser) {
      // not logged in so redirect to login page with the return url
      this.router.navigate([PAGE_ROUTES.LOGIN_ROUTE]);
      return false;
    }
    // logged in so return true
    return true;
  }
}

而且我希望能够使用用户权限来允许他们进入或不进入页面。

类似的东西:

if(!this.currentUser.rights['dashboard'] && state.url === PAGES_ROUTES.DASHBOARD) {
  this.router.navigate([PAGE_ROUTES.DEFAULT_PAGE]);
  return false;
}

但是如果我使用state.url,我不为什么,但是我有一个无限循环(DEFAULT_PAGE与DASHBOARD不同),有什么方法可以让我查看路线并查看用户是否拥有权限要在此身份验证保护服务中转到此路由?

我想避免在应用路由中使用角色,这就是为什么我尝试使用身份验证保护的原因。

谢谢。

编辑1:

const routes: Routes = [
  {
    path: '',
    redirectTo: PAGE_PATHS.DASHBOARD,
    pathMatch: 'full',
    canActivate: [AuthenticationGuardService]
  },
  { path: PAGE_ROUTES.LOGIN_ROUTE, component: LoginComponent },
  { path: PAGE_ROUTES.PASSWORD_ROUTE, component: PasswordComponent },
  {
    path: '**',
    redirectTo: PAGE_PATHS.DASHBOARD,
    pathMatch: 'full',
    canActivate: [AuthenticationGuardService]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
angular authentication routes angular2-routing angular2-services
1个回答
0
投票

您需要向Routes数组添加新路径:

const routes: Routes = [
    ...
    { path: PAGE_ROUTES.DEFAULT_PAGE, component: /*your component*/ },
    { path: PAGE_ROUTES.DASHBOARD, component: /*your component*/ },
    ...

由于缺少此路径,您的重定向落入“ **”路由,无限循环

© www.soinside.com 2019 - 2024. All rights reserved.