角度延迟加载路由总是转到通配符模块



我正在开发一个具有多个模块的新 Angular 应用程序。我仍在努力使我的路由正确。在下面的(简化)示例中,我想延迟加载StoreModule。如果没有给出 url,我希望我的应用程序重定向到 /store .如果提供的 URL 无效,我希望显示我的NotFoundComponent。但是,在我当前的配置中,无论 URL 如何,始终显示NotFoundComponent。你们看到我做错了什么吗?

这是我app.module.ts文件,如果无法进行 URL 匹配,我希望它仅使用 NotFoundModule 中提供的RouterModule

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.如果我注释掉app.module.ts模块中的NotFoundModule,这一切都按预期工作。

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 { }

您的路由器设置看起来正常。要看的一件事是您在"仪表板"中有AuthGuard,必须重定向并且重定向 URL 一定是错误的,因此,您将被重定向到 NotFoundComponent。

希望这能解决您的问题。

如果没有给出 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
]),

最新更新