【问题标题】:Concat Angular 2 routesConcat Angular 2 条路线
【发布时间】:2017-03-23 11:14:11
【问题描述】:

有没有办法在 Angular 2 中连接两个路由数组?我需要将路由定义拆分为不同的文件,因此我有多个要合并的变量。 我试过使用数组推送,但没有运气。

即(这是有效的):

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full',
  },
  {
    path: '',
    component: LayoutComponent,
    data: {
      title: 'Home'
    },
    children: [
      {
        path: 'dashboard',
        loadChildren: './dashboard/dashboard.module#DashboardModule'
      },
      {
        path: 'page1',
        loadChildren: './page1/page1.module#Page1Module'
      }
    ]
  }
];

function getRoutes(){
  return routes;
};


@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

但这不起作用(导航到 /page1 时出现“找不到第 1 页模块”错误)。

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full',
  },
  {
    path: '',
    component: LayoutComponent,
    data: {
      title: 'Home'
    },
    children: [
      {
        path: 'dashboard',
        loadChildren: './dashboard/dashboard.module#DashboardModule'
      }
    ]
  }
];

function getRoutes(){
  // Actually customRoutes will be splited in its own file and imported
  let customRoutes = {
    path: 'page1',
    loadChildren: './page1/page1.module#Page1Module'
  }

  routes[1].children.push(customRoutes)
  return routes;
};


@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

我做错了吗?

【问题讨论】:

  • 请清除。没有合并的第一个简单示例甚至不起作用吗?
  • 你没有在RouterModule.forRoot(routes)中使用函数getRoutes()
  • 是的,抱歉,应该是 RouterModule.forRoot(getRoutes()),但我无法编辑我的答案。 function getRoutes() 也应该是 export function getRoutes()。第一个例子有效,第二个无效。
  • 您是否设法解决了这个问题?我也需要连接我的路线。

标签: javascript angular routes


【解决方案1】:

只需创建一个新变量。

function getRoutes(){
  // Let's make this an array
  let customRoutes: Routes = [{
    path: 'page1',
    loadChildren: './page1/page1.module#Page1Module'
  }]
  var allRoutes: Routes = []; // Push all routes into this
  routes.forEach(r => allRoutes.push(r));
  // Even better would be to do this with a condition in the forEach instead of hardcoding the index
  allRoutes[1].children.push(customRoutes);
  // allRoutes.push(otherCustomRoutes);
  return allRoutes;
};

@NgModule({
  imports: [ RouterModule.forRoot(getRoutes()) ],
  exports: [ RouterModule ]
})

我使用的是 Angular 8,所以也许这在过去不起作用?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2023-04-04
    • 2022-09-28
    • 1970-01-01
    • 2017-04-12
    • 2023-03-04
    • 2017-07-21
    相关资源
    最近更新 更多