首页 > 解决方案 > Angular 路由器:带参数的 loadChildren

问题描述

在我的角度路由器中,我想根据 url 中的参数延迟加载不同的模块。这是我的设置的psudo路线:

path: ':slug',
loadChildren: async () => {
  
  const SLUG = "How do I get the :slug param from the URL"?;

    switch (SLUG) {
      case 'first':
        return (await import('./pages/first-page/first-page.module')).FirstPageModule;
        break;
      case 'second':
        return (await import('./pages/second-page/second-page.module')).SecondPageModule;
        break;
      default:
        return (await import('./pages/default-page/default-page.module')).DefaultPageModule;
    }
},

我尝试使用解析器和守卫——不幸的是,它们在路由激活后触发,因此我无法事先访问参数。有任何想法吗?

标签: angularlazy-loadingangular-router

解决方案


slug为like 创建一个模块:const routes: Routes = [ { path: 'slug', loadChildren: () => import('./slug/slug.module').then(m => m.SlugModule) } ]; 然后,在 中SlugModule,为组件添加路由,例如: const routes: Routes = [ { path: 'first', component: FirstComponent }, { path: 'second', component: SecondComponent } ];


推荐阅读