我正在开发一个具有多个模块的新Angular应用程序。我仍然在努力让我的路由正确。在下面(简化)示例中,我想延迟加载StoreModule
。如果没有给出url,我希望我的应用程序重定向到/store
。如果提供的网址无效,我希望显示NotFoundComponent
。但是,在我当前的配置中,无论URL如何,都会始终显示NotFoundComponent
。你们看到我做错了吗?
这是我的app.module.ts
文件,如果没有匹配的网址,我希望它只使用RouterModule
中提供的NotFoundModule
。
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AuthModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'store', pathMatch: 'full'},
{ path: 'store', loadChildren: 'app/store/store.module#StoreModule'},
{ path: 'login', component: LoginComponent },
]),
LoginModule,
NotfoundModule,
],
bootstrap: [AppComponent],
exports: [RouterModule]
})
export class AppModule { }
这是我的StoreModule
。如果我在NotFoundModule
模块中注释掉app.module.ts
,则这一切都按预期工作。
store.module.ts
@NgModule({
imports: [
AuthModule,
CommonModule,
SharedModule,
RouterModule.forChild([
{ path: '', pathMatch: 'full', redirectTo: 'dashboard' },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
]),
],
declarations: [StoreTemplateComponent, DashboardComponent]
})
export class StoreModule { }
notfound.module.ts
@NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{
path: '**',
component: NotfoundComponent
}
])
],
declarations: [ NotfoundComponent ],
})
export class NotfoundModule { }
答案 0 :(得分:0)
您的路由器设置看起来不错。要注意的一件事是 你在'仪表板'中有AuthGuard,它必须重定向 并且重定向URL必须是错误的, 所以你被重定向到NotFoundComponent。
希望这能解决你的问题。
答案 1 :(得分:0)
如果没有给出url,我希望我的应用程序重定向到/ store。如果给出了无效的URL,我希望显示我的NotFoundComponent。
如果这是要求,则需要删除 notfound.module.ts 。或者你需要像现在的设置一样懒得加载它你没有在你的路线中加载它并通过在应用程序模块中添加它预先加载它并将所有路由视为外卡。
您可以拥有 NotfoundComponent 并将其添加到现有路线中。
RouterModule.forRoot([
{ path: '', redirectTo: 'store', pathMatch: 'full'},
{ path: 'store', loadChildren: 'app/store/store.module#StoreModule'},
{ path: 'login', component: LoginComponent },
{ path: '**', component: NotfoundComponent } // this should work
]),