Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Routing Lazy Load Children's Children

I am currently stuck on how Angular Routing works and need some help. Basically in my project, I have one core module which used for loading the all the root routes, the home is following:

const routes: Routes = [
  {path: '', redirectTo: '/login', pathMatch: 'full'},
  {path: 'user', loadChildren: 'app/userManagement#UserModule', pathMatch: 'full',canActivate: [AuthGaurd] },
  {path: '**', component: PageNotFoundComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})


export class AppRoutingModule {}

And in app/userManagement folder I have an index.ts used for imports and declare all the modules:

@NgModule({
  imports: [
    SharedModule,
    UserManagementRoutingModule
  ],
  declarations: [UserHomeComponent, UserListComponent, UserDetailsComponent]
})
export class UserModule {
}

And my child routing put inside of the UserManagementRoutingModule:

const routes: Routes = [
  {
    path: '',
    component: UserHomeComponent,
  },
  {
    path: 'userDetails',
    component: UserDetailsComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UserManagementRoutingModule {
}

In this way when I go to http://hostname/user it will direct to my UserHomeComponent component, however if i go to http://hostname/user/userDetails Angular didn't redirect to that page. How should I edit my code so that I can access the userDetailsComponent?

Thanks

like image 908
Terry Zhang Avatar asked Oct 16 '17 14:10

Terry Zhang


1 Answers

When lazy loading, best practice is to define all routed under a blank path as children. Also, you need to be sure to import CommonModule or BrowserModule in your @ngModules (in your case, since it's a child you will use common).

@NgModule({
  imports: [
    CommonModule,
    SharedModule,
    UserManagementRoutingModule
  ],
  declarations: [UserHomeComponent, UserListComponent, UserDetailsComponent]
})
export class UserModule {
}

The above will ensure components are properly loaded, and the below will provide best practice routing.

const routes: Routes = [
  {
    path: '',
    children: [
      { path: '', component: UserHomeComponent },
      { path: 'userDetails', component: UserDetailsComponent }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UserManagementRoutingModule {
}
like image 126
Z. Bagley Avatar answered Nov 15 '22 18:11

Z. Bagley