Angular 延迟加载 : route to a specific feature component

标签 angular typescript

我正在尝试实现 Angular 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中的路由或链接应该如何处理?结构化以实现这一目标?

你可以从我下面的代码中注意到,我的延迟加载路由只指向模块,但是 ''路由 - 默认触发 - 并不总是用户想要访问的(如果他/她点击“卖出”,他想查看卖出组件,反之亦然“买入”) 并且我想避免为每个模块创建子主页...

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

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:如有需要,我会提供任何说明

最佳答案

您可以为功能模块创建一个单独的路径,例如app.routing module 中的'inventory'。功能模块将适本地加载其子路由 (buy and sell)。有了这个,你不需要在 app.routing.module

中指定 FeatureModule 的所有子路由

应用程序路由

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

关于 Angular 延迟加载 : route to a specific feature component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51416354/

相关文章:

css - 将背景图像添加到 mat-dialog

angular - typescript 错误 :Object. 来自条目 typescript 错误

Angular 2 : How to handle *ngif in option select

typescript - 如何为 TypeScript 导入 RXJS 类型

带有 *ngFor ARIA 标签的 Angular Material mat-option 在 Lighthouse 失败

ios - iOS 中的 Ionic 4 Http 请求失败

javascript - 如何捕获子组件 setter 抛出的错误?

angular - ionic 单一语言

javascript - 2 个不同的阵列到单个阵列组

angular - 如何在 Angular 4 中实现 strictNullChecks