【问题标题】:Angular 7 router '**' wildcard with lazy load module and child routes not working?带有延迟加载模块和子路由的Angular 7路由器'**'通配符不起作用?
【发布时间】:2019-01-20 17:43:04
【问题描述】:

我正在尝试使用来自 Angular 路由器的通配符“**”创建默认路由。该默认路由将加载一个惰性模块,然后它必须解决自己的路由。问题是当我有以下配置时,它没有按预期解决:

export const routes = [
  {
    path: '',
    component: 'DashboardComponent'
  },
  {
    path: '**',
    loadChildren: './lazy/lazy.module#LazyModule'
  }
];

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  declarations: [AppComponent]
  bootstrap: [AppComponent]
})
export class AppModule {}

const routes = [
  {
    path: '', 
    component: MainComponent
  }
  {
    path: 'hello',  // hoping to pick up the wildcard and resolve the route
    component: HelloComponent
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [
    AnyComponent,
    EditComponent
  ]
})
export default class LazyModule {}

例如。对于 mydomain.com/hello,它不会向我显示 HelloComponent,而是向我显示 MainComponent。

我的配置有问题还是不应该这样工作?

提前致谢。

【问题讨论】:

  • 你试过mydomain.com/hello/hello。我的猜测是它解析了第一个路径值的通配符,然后考虑了下一层路径的惰性模块路由方案,并且由于/hello 的第二部分什么都不是,所以它解析为第一条路由。我以前从未在通配符路由上看到过延迟加载,但我认为您必须使用某种类型的辅助路径部分才能在该子模块中进一步解析
  • @TimKlein 感谢您的帮助。我刚试过你告诉我的,因为它在世界上都很有意义,但它仍然不起作用。似乎它以 /hello/hello 作为根路径并始终显示 LazyComponent。如果不是太麻烦,你可以做一个测试吗?对不起我的英语不好。

标签: angular lazy-loading wildcard angular-router


【解决方案1】:

惰性模块需要两个路由配置。 appModule 中的第一个告诉角度何时加载模块。第二个在惰性特性模块中,告诉 Angular 何时显示特定组件。

在您的情况下,将 appModule 路由的路径更改为 hello。这告诉 Angular 在看到 hello url 时下载惰性模块。 从第二个配置开始,将其留空。这告诉 Angular 在看到hello url 后面的空字符串时加载组件

AppModule

export const routes = [
  {
    path: '',
    component: 'DashboardComponent'
  },
  {
    path: 'helllo', <-- change this
    loadChildren: './lazy/lazy.module#LazyModule'
  }
];

LazyModule

const routes = [
  {
    path: '', 
    component: LazyComponent // I do not know what this is. The components are not lazy. Modules are
  }
  {
    path: '',  <-- change this
    component: HelloComponent
  }
];

我在您的代码中看到您有一个 LazyComponent。我不知道你想用这个实现什么,但组件并不懒惰。模块是。

【讨论】:

【解决方案2】:

我相信您必须重定向到实际路线。有一些与此相关的主题,here is one。同样根据Angular's examples,您可能必须从 LazyModule 导出您的 RouterModule。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多