如何从Angular中的数组初始化路由?

问题描述 投票:0回答:1

我想为存储在单独数组中的每个区域初始化路由:

regions: any[] = [
    { cityEng: 'moscow', cityRus: 'Москва', region: 'Моск', value: 'Москва и МО', isTop: true },
    { cityEng: 'Saint-Petersburg', cityRus: 'Санкт-Петербург', region: 'Санкт-Петербург', value: 'Санкт-Петербург и ЛО', isTop: true },
    { cityEng: 'Novosibirsk', cityRus: 'Новосибирск', region: 'Новосибирская', value: 'Новосибирская обл.' }
]; 

如果我不是从类似数组的路径创建路由,则:

var routes: Routes = [
  {
    path: '', pathMatch: 'full', canActivate: [MetaGuard],
    loadChildren: () => import('./components/main-page/main-page.module').then(m => m.MainPageModule)
  },
  {
    path: 'moscow',
    canActivateChild: [MetaGuard],
    loadChildren: () => import('./components/news/news.module').then(m => m.NewsModule)
  }
];

有效。

但是,如果我插入具有完全相同属性的路由对象,则会给我404错误...

var routes: Routes = [
  {
    path: '', pathMatch: 'full', canActivate: [MetaGuard],
    loadChildren: () => import('./components/main-page/main-page.module').then(m => m.MainPageModule)
  }
];

regions.forEach(region => {
  var regionRoute = {
    pathMatch: "full",
    path: region.cityEng.toLowerCase(), 
    loadChildren: () => import('./components/main-page/main-page.module').then(m => m.MainPageModule),
    data: { region: region }
  };

  routes.push(regionRoute);
});
angular angular-router
1个回答
0
投票

问题是由于404路线(路径:“ **”),它必须是您的路线列表中的最后一个!希望对任何人有帮助

  // !!! HAS TO BE THE LAST ONE
  // Show the 404 page for any routes that don't exist 
  {
    path: '**', canActivateChild: [MetaGuard], 
    loadChildren: () => import('./not-found/not-found.module').then(m => m.NotFoundModule)
  }
© www.soinside.com 2019 - 2024. All rights reserved.