角延迟加载:路由到特定要素组件

时间:2018-07-19 07:05:01

标签: angular typescript

我正在尝试实现有角度的6延迟加载,我想在我的主页面中建立一个链接,将每个链接指向一个特定的要素组件。

我的项目的层次结构如下:

app.module.ts
|__homepage.component.ts
|__options.component.ts
|__feature.module.ts
   |__buy.component.ts
   |__sell.component.ts

用户可以从homepage.component直接访问buy.componentsell.component

homepage.component中的路线或链接应如何构造以实现此目的?

从下面的代码中您可以注意到,我的延迟加载路由仅指向模块,但是''路由(默认情况下已触发)并不总是用户希望访问的路由< em>(如果他/她单击“ sell”(销售),则他想查看“ sell”(销售)组件,反之亦然,以“ buy”(买))),我想避免为每个模块创建子主页...

这是我到目前为止的路线代码:

  

app.routing.ts

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'options',
    component: OptionsComponent
  },
  {
    path: 'buy',
    loadChildren: "../app/posts/feature.module#FeatureModule"
  },
  {
    path: 'sell',
    loadChildren: "../app/posts/feature.module#FeatureModule"
  }
];
  

feature.routing.ts

{
    path: '',
    redirectTo: '/buy',
    pathMatch: 'full'
  },
  {
    path: 'buy',
    component: BuyComponent
  },
  {
    path: 'sell',
    component: SellComponent
  }

PS:如有需要,我将为您进行澄清

2 个答案:

答案 0 :(得分:3)

您可以在path中为功能模块创建单独的'inventory',例如app.routing module。并且功能模块将适当地加载其子路由(buy and sell)。这样,您无需在FeatureModule

内指定app.routing.module的所有子路由

app.routing

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'options',
    component: OptionsComponent
  },
  {
    path: 'inventory',     // some other path to load feature module
    loadChildren: "../app/posts/feature.module#FeatureModule"  
  }
];

编辑:

所以您到功能模块的路线看起来像

routerLink="/inventory/buy"routerLink="/inventory/sell"或简单的routerLink="/inventory",它将重定向到/inventory/buy

答案 1 :(得分:2)

制作子要素模块时,路线也会更改。

您应该为功能模块创建路由,为组件创建子路由。

示例:

app.routing.ts

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'options',
    component: OptionsComponent
  },
  {
    path: 'feature',
    loadChildren: "../app/posts/feature.module#FeatureModule"
  }
];

feature.routing.ts

  {
    path: '',
    redirectTo: '/buy',
    pathMatch: 'full'
  },
  {
    path: 'buy',
    component: BuyComponent
  },
  {
    path: 'sell',
    component: SellComponent
  }

导航至路线:

routerLink="/feature/buy"

this.router.navigateByUrl("/feature/buy");