如何在路由器配置中调用函数?

时间:2018-03-02 14:34:44

标签: angular

我正在使用一个功能来帮助我建立路由器配置。该功能使路线更美观,更有条理,易于维护,但我遇到了问题。

看起来路由不在routes数组中,因为我没有错误并且路由正在构建正确,但是当我测试并编写一个模型的URL时,我被重定向到NotFound页面。

我的助手功能:

function getAngularRouteStringPattern(model: Function) {
    let splitedName: string[] = model.name.split(/(?=[A-Z])/);
    return splitedName.join('-').toLowerCase();
}

function getLazyPath(model: Function) {
    let modelPascalCase = model.name;
    let modelAngularPattern = getAngularRouteStringPattern(model);
    return `app/modules/sistema/${modelAngularPattern}/${modelAngularPattern}.module#${modelPascalCase}Module`;
}

function getRoute(model: Function): Route {
    return <Route>{
        path: getAngularRouteStringPattern(model),
        loadChildren: getLazyPath(model)
    }
}

function getRoutes(models: Function[], staticRoutes?: Route[]): Route[] {
    let routes: Route[] = staticRoutes ? staticRoutes : [];

    models.forEach(model => {
        routes.push(getRoute(model));
    });

    return routes;
}

模型数组:

const models = [
            User,
            Employer,
            Order
            ...
        ];

路由数组:

export const routes: Routes = [
    {
        path: '', component: AppComponent,
        canActivate: [AuthGuard],
        children: [
            {
                path: '',
                canActivateChild: [AuthGuard],
                children: getRoutes(models, [
                    {
                        path: '', redirectTo: 'about', pathMatch: 'full'
                    },
                    {
                        path: 'about',
                        component: AboutComponent
                    },
                    {
                        path: 'logoff',
                        component: LogoffComponent
                    }
                ])
            },
            {
                path: '**', component: NotFoundComponent
            }
        ]
    }
];

1 个答案:

答案 0 :(得分:0)

经过一段时间搜索我的路线后发现了什么问题。

如角度页面上描述的那样,关于router配置,配置中路由的顺序很重要,这是设计的,所以当我加入模型路由前面的静态路由时,'调用带有NotFoundPage的**'关键字,因为它在模型路由之前。

现在,这是我的路由器代码:

export const routes: Routes = [
    {
        path: '', component: AppComponent,
        canActivate: [AuthGuard],
        children: [
            {
                path: '',
                canActivateChild: [AuthGuard],
                children: [
                    {
                        path: '', redirectTo: 'about', pathMatch: 'full'
                    },
                    {
                        path: 'about',
                        component: AboutComponent
                    },
                    ...getRoutes(models),
                    {
                        path: 'logoff',
                        component: LogoffComponent
                    }
                ]
            },
            {
                path: '**', component: NotFoundComponent
            }
        ]
    }
];