重定向到 Angular 2 中第一个允许的路线?

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

我有以下路线配置:

const routes: Routes = [
  { path: '', redirectTo: 'customers', pathMatch: 'full' },
  { path: 'customers', component: CustomerListComponent, canActivate: [CustomerGuard] },
  { path: 'products', component: ProductListComponent, canActivate: [ProductGuard] },
  { path: 'sales', component: SalesListComponent, canActivate: [SalesGuard] }
]; 

问题是,我没有“仪表板”,只有域管理页面,尽管每个授权用户都可以访问至少其中一个页面,但所有用户都无法使用它们。

是否有一个选项可以激活:重定向到第一条路线?或者我需要在路径“/”下编写一个虚拟组件来根据用户角色进行动态重定向?

angular angular2-routing roles
2个回答
1
投票

无法重定向到第一个可用的路线。 使用虚拟路由和虚拟组件,仅根据角色进行重定向是正确的方法。您还可以在守卫中进行重定向https://angular.io/docs/ts/latest/guide/router.html#!#guards但虚拟路由无论如何都需要一个组件。

您还可以使用

router.resetConfig()
根据角色加载路由,如基于外部数据的动态路由

所示

0
投票

要重定向到像

MyComponent
这样的组件内第一个可以激活的路由,可以动态修改该组件对应的路由对象。具体方法如下:

// Import ActivatedRoute and Router modules to access the current route and navigate
import { ActivatedRoute, Router } from '@angular/router';

// Inside the constructor of MyComponent
constructor(private router: Router, private activatedRoute: ActivatedRoute) { }

// Inside the ngOnInit() method
ngOnInit() {
  // Get the child routes
  const childRoutes = this.activatedRoute.routeConfig.children;

  // Find the first child route with permissions
  const firstRouteWithPermissions = childRoutes.find(route => {
    const permissions = route.data?.permissions?.only;
    return permissions && permissions.length > 0;
  });

  // If a route with permissions is found, navigate to it
  if (firstRouteWithPermissions) {
    const path = firstRouteWithPermissions.path;
    this.router.navigate([path], { relativeTo: this.activatedRoute });
  }
}

此代码在

MyComponent
的子路由中搜索已定义权限的第一条路由并导航到它。

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