使用JSON对象动态构建子路由

时间:2017-12-05 14:55:23

标签: angular angular2-routing

我已经硬编码了我的孩子路线,如下所示。但我想使用JSON对象构建它,即下面应动态添加,其组件应自动导入。 JSON对象也可以存储在文件中。有没有办法达到要求。

  [
    { path: 'step1', component: aComponent },
    { path: 'step2', component: bComponent },
    { path: 'step3', component: cComponent },
    { path: 'step4', component: dComponent },
    { path: 'step5', component: eComponent },
    { path: 'step6', component: fComponent }
  ]

最终结果应如下所示。

 export const abcRoutes: Routes = [
      {
        path: '',
        component: abcLandingComponent,
        children: [
          { path: 'step1', component: aComponent },
          { path: 'step2', component: bComponent },
          { path: 'step3', component: cComponent },
          { path: 'step4', component: dComponent },
          { path: 'step5', component: eComponent },
          { path: 'step6', component: fComponent }
        ]
      }

1 个答案:

答案 0 :(得分:0)

你可以将它们导出为这个吗?

import { aComponent } from './aComponent.componet';
import { bComponent } from './bComponent.componet';    
etc...

// or use a barrel file. 

import { aComponent, bComponent, etc.. } from './components';

export const childRoutes = [
  { path: 'step1', component: aComponent },
  { path: 'step2', component: bComponent },
  { path: 'step3', component: cComponent },
  { path: 'step4', component: dComponent },
  { path: 'step5', component: eComponent },
  { path: 'step6', component: fComponent }
];

然后将它们导入为?

import { childRoutes } from './routes';

export const abcRoutes: Routes = [
{
  path: '',
  component: abcLandingComponent,
  children: childRoutes
}];