首页 > 解决方案 > 基于登录用户类型的导航 - Angular

问题描述

我正在为不同的客户端类型(businessClient、individualClient)创建具有单独仪表板的应用程序。客户端类型带有会话上下文,因此在导航到仪表板开始之前就知道了。我想使用角度路由器机制根据客户端类型加载适当的仪表板。

我目前的实现:

路由

{
        path: 'dashboard',
        component: DashboardComponent,
        children: [
            {
                path: '',
                pathMatch: 'full',
                redirectTo: 'indv-client-data'
            },
            {
                path: 'indv-client-data',
                canActivate: [IsProperClientTypeGuard],
                resolve: {
                    clientData: IndvClientDataResolver
                },
                component: IndvClientDataComponent,
                data: {
                    clientType: ClientType.INDIVIDUAL,
                    redirectionUrl: 'busi-client-data'
                }
            },
            {
                path: 'busi-client-data',
                canActivate: [IsProperClientTypeGuard],
                resolve: {
                    clientData: BusiClientDataResolver
                },
                component: BusiClientDataComponent,
                data: {
                    clientType: ClientType.BUSINESS,
                    redirectionUrl: 'indv-client-data'
                }
            }
        ]
    }

警卫

public canActivate(route: ActivatedRouteSnapshot): boolean {

        const clientType = route.data['clientType'];
        const redirectionUrl = route.data['redirectionUrl'];

        if (this._sessionContext.clientType === clientType) {
            return true;
        } else {
            this._router.navigate([redirectionUrl]);
        }
    }

我的解决方案运行良好,涵盖了我的所有需求,但我觉得它非常难看(尤其是 redirectionUrl 数据参数)。有没有更好的方法来使用角度路由器来实现相同的结果?

标签: angularangular-routingangular-routerangular-router-guards

解决方案


您可以跳过两条不同的路线“dashboard/indv-client-data”和“dashboard/busi-client-data”。如果它使用户无法访问两者。相反,只有一个仪表板路线。在仪表板页面内,您可以检查它是什么类型的用户,并在两个不同的仪表板组件之间进行选择。一个用于indv,一个用于busi。路由器会简单得多。只需要顶部路线。当然,您仍然需要实现这两个仪表板,但您最终会得到更简单的路由并且没有重定向。


推荐阅读