gpt4 book ai didi

AOT的Angular 4动态路由问题

转载 作者:太空狗 更新时间:2023-10-29 18:31:16 25 4
gpt4 key购买 nike

我有一个应用程序,我需要根据用户点击的 URL 重定向到不同的组件,假设如果它是 localhost/login 它应该重定向到路由 localhost/login/#/login,如果 localhost/user 然后 localhost/user/#/spreadsheet,这在没有 AOT 的情况下工作正常,但没有 AOT,这是我的函数来获取重定向路由:

export function baseHref() {
return ((document.location.pathname == '/login/') ? 'login' : ((document.location.pathname.split('/')[3] == 'edit') ? 'edit' : ((window.innerWidth >= 720) ? 'spreadsheet' : 'two-panel')));
}

这是我的路线:

export const rootRouterConfig: Routes = [
// If path is not defined it will redirect to spreadsheet
{ path: '', redirectTo: baseHref, pathMatch: 'full' },
{ path: 'spreadsheet', component: ContactParent },
{ path: 'two-panel', component: ContactParent },
{ path: 'login', component: Login },
{ path: 'login/step1', component: LoginStep1 },
{ path: 'login/step2', component: LoginStep2 },
{ path: 'edit', component: EditSingleContact },
{ path: 'share', component: EditSingleContact }
];

这里总是重定向到two-panel 路由

最佳答案

这可以通过使用函数工厂向 ROUTES 提供路由定义来解决...(在 Angular 4.1.2 上测试)

修改您的 AppModule (app.module.ts):

更改导入数组中的 RouterModul.forRoot

imports: [
RouterModule.forRoot(routes)
...

RouterModule.forRoot([])

在提供者数组中添加这两个提供者:

... ANALYZE_FOR_ENTRY_COMPONENTS
} from '@angular/core';
... ROUTES,
} from '@angular/router';
...
providers: [
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes},
{provide: ROUTES, multi: true, useFactory: getRoutes},
...

定义工厂函数(在 app.module.ts 文件的顶部):

export function getRoutes() {
return routes;
}

也许您还需要创建新文件,例如:app.routes.ts 并将您的路由定义放在那里

export const routes: Routes = [
{
path: '',
...

并将其导入 AppModule (app.module.ts)。

import { routes } from './app.routes';

关于AOT的Angular 4动态路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43839949/

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