简体   繁体   中英

Angular 8 - Lazy Loading - Weird Child Route Behaviour

I have an angular 8 application, with feature modules each containing a *-routing.module.ts file containing the routing to it's individual components.

At present, I've got 2 feature modules, one called "Tasks" and one called "Clients".

Both are set up the same way. Here is my app.routing.ts :

// Task Pages
{ path: 'tasks', loadChildren: './tasks/tasks.module#TasksModule' },

// Client Pages
{ path: 'clients', loadChildren: './clients/clients.module#ClientModule' },

Now for some reason, these two modules behave weirdly. Within clients-routing.module.ts , I prepend the routes with "clients":

  const routes: Routes = [
    { path: 'clients', component: ClientListComponent, canActivate: [AuthGuard] },
    { path: 'clients/new', component: ClientCreateComponent, canActivate: [AuthGuard]},
    { path: 'clients/:id', component: ClientDetailComponent, canActivate: [AuthGuard]},
    { path: 'clients/:id/edit', component: ClientEditComponent, canActivate: [AuthGuard]},
];

And everything works as expected. Navigating to http://baseurl/clients lists all clients, navigating to http://baseurl/clients/1 navigates to the correct client detail and so on.

However, with the tasks-routing.module.ts , if I include the tasks prepend like in the clients file, then it doesn't work, none of the routes work as expected, instead, I need to do this:

    const routes: Routes = [
    { path: '', component: TaskListComponent, canActivate: [AuthGuard] },
    { path: 'new', component: TaskCreateComponent, canActivate: [AuthGuard] },
    { path: ':id', component: TaskDetailComponent, canActivate: [AuthGuard] },
];

At which point, the expected routes work, such as http://baseurl/tasks listing all tasks, http://baseurl/tasks/23 show task 23 detail and so on.

Why are they different? I can't seem to see any reason why the two module's routing would differ.

This looks like the difference between using RouterModule.forRoot() and RouterModule.forChild() when registering the route.

I suspect your client route is using the forRoot method and the tasks is using the forChild method hence the difference.

Angular style guide recommends:

Only call RouterModule.forRoot() in the root AppRoutingModule (or the AppModule if that's where you register top level application routes). In any other module, you must call the RouterModule.forChild method to register additional routes.

https://angular.io/guide/router

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM