Concat Angular 2路线

时间:2017-03-23 11:14:11

标签: javascript angular routes

有没有办法在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时,我收到“找不到Page 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 ]
})

我做错了吗?

1 个答案:

答案 0 :(得分:0)

只需创建一个新变量。

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,所以也许这在过去不起作用?