问题
I'm trying to create a default route using the wildcard '**' from Angular's router. That default route will load a lazy module and then it will have to solve its own routes. The problem is that when I have the following configuration it does not resolve as expected:
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 {}
For example. With mydomain.com/hello it does not show me the HelloComponent, it shows me the MainComponent.
Is there something wrong with my configuration or should it not work like this?
Thanks in advance.
回答1:
The lazy modules require two routing configuration. The first one which is in the appModule tells the angular when to load the module. The second one which is in the lazy feature module, tells the angular when to display a specific component.
In your case, change the path of the appModule routing to be hello
. This tells the angular to download the lazy module when sees the hello
url.
As of the second configuration, leave it empty. This tells angular to load the component when it sees an empty string following the 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
}
];
I saw in your code that you have a LazyComponent. I do not know what you are trying to achieve with this but the components are not lazy. Modules are.
回答2:
I believe you have to redirect to an actual route. There are a few topics related to this, here is one. Also per Angular's examples, you might have to export your RouterModule from LazyModule.
来源:https://stackoverflow.com/questions/54279174/angular-7-router-wildcard-with-lazy-load-module-and-child-routes-not-workin