angular - 使用 Angular 延迟加载模块设置默认路由
问题描述
我用 Angular 延迟加载模块,但是如果我导航到 URL 而不提供路由路径,例如http://localhost:4200
它会about.module
在我期望加载的时候加载我的home.module
。急切地加载模块按预期工作。
每个模块都有一个*-routing.module
:
应用程序路由.module.ts
/* ... */
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./modules/home/home.module').then(m => m.HomeModule)
},
{
path: 'about',
loadChildren: () => import('./modules/about/about.module').then(m => m.AboutModule)
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: '**',
redirectTo: 'page-not-found'
}
];
@NgModule({
imports: [
RouterModule.forRoot(
routes
/* ... */
)
],
exports: [RouterModule]
})
/* ... */
家庭路由.module.ts
/* ... */
const routes: Routes = [
{
path: '',
component: HomeComponent,
data: {
title: 'Home'
}
}
];
@NgModule({
imports: [
/* ... */
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
/* ... */
about-routing.module.ts
/* ... */
const routes: Routes = [
{
path: '',
component: AboutComponent,
data: {
title: 'About'
}
}
];
@NgModule({
imports: [
/* ... */
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
/* ... */
我尝试过并且适用于旧版本 Angular 的其他解决方案似乎不起作用:
在这种情况下,我正在使用 Angular 8+。
解决方案
非常及时,因为我在从 7.2.5 升级到 8.1.3 后似乎遇到了同样的问题。在我非常确定它进行了重定向之后,它工作得很好,在过去的 12-24 小时之后,一些事情无意中改变了我觉得我疯了的地方。如果我直接进入 /home 没有问题,但 localhost:4200 不会重定向,但没有任何错误。
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: () => import(`./shell/home/home.module`).then(m => m.HomeModule) }
]),
home.module.ts
import { HomeComponent } from './home.component';
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { HomeRoutingModule } from './home-routing-module';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [
CommonModule,
HomeRoutingModule
],
declarations: [
HomeComponent
],
exports: [RouterModule],
schemas: [ NO_ERRORS_SCHEMA ]
})
export class HomeModule { }
家庭路由模块.ts
import { Routes } from '@angular/router';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { NgModule } from '@angular/core';
const routes: Routes = [
{ path: '', component: HomeComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
推荐阅读
- javascript - 在 createApi redux-toolkit 中记录
- javascript - 如何从 vanilla JS 事件监听器修改 Vue 数据?
- packaging - 如何在打包的应用程序中注册 Shell 命名空间扩展?
- python - 在数据框选择查询 Pyspark 中访问局部变量
- java - 使用 Firebase 实时数据库和 Android (Java) 时 Firebase API 的异步行为问题
- javascript - 获取具有对应值的对象属性名称
- gstreamer-1.0 - 拆分到文件接收器时 gstreamer 性能提高
- sql - SQL - 有效地比较特定 ID 的日期
- javascript - 为每个元素设置不同的 React Popper 工具提示
- mysql - 在 liquibase 中删除存储过程的正确方法是什么