代码之家  ›  专栏  ›  技术社区  ›  lahsrah

在何处声明角捕获所有(未找到)路由

  •  3
  • lahsrah  · 技术社区  · 6 年前

    我有一条主线 app.routing.module.ts 因此:

     const routes: Routes = [
      { path: 'home',  component: HomeComponent },
      { path: 'login', component: LoginComponent },
      { path: '', redirectTo: '/home', pathMatch: 'full' }
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes),
      ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}
    

    然后是几个子路由模块:

    const routes: Routes = [
        { path: 'AbcRoute1', component: AbcRoute1Component },
        { path: 'AbcRoute2', component: AbcRoute2Component }
    ];
    
    @NgModule({
        imports: [ RouterModule.forChild(routes) ],
        exports: [ RouterModule ]
    })
    export class AbcRoutingModule {}
    
    const routes: Routes = [
        { path: 'DefRoute1', component: DefRoute1Component },
        { path: 'DefRoute2', component: DefRoute2Component }
    ];
    
    @NgModule({
        imports: [ RouterModule.forChild(routes) ],
        exports: [ RouterModule ]
    })
    export class DefRoutingModule {}
    

    我指的是“包罗万象”路线:

    { path: '**', redirectTo: '/home', pathMatch: 'full' }
    

    如果我把它放在 AppRoutingModule ,如果它不匹配 批准模块 。例如,我无法 https://myapp/DefRoute1 定义于 DefRoutingModule

    如果我把它放进去 AbcRoutingModule ,那么所有的本地路线都能正常工作 解布线模块 不起作用。

    我应该把它放在哪里,这样只有当我的所有路由模块都无法匹配url时,它才会匹配?

    1 回复  |  直到 3 年前
        1
  •  7
  •   lahsrah    6 年前

    确保 AppRoutingModule (根路由模块)在模块导入中声明为最后一个。然后在其中声明catch-all通配符。文档链接: https://angular.io/guide/router#routing-module-order

    @NgModule({
      declarations: [
        //...
      ],
      imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,    
        HttpClientModule,
        // all other modules including any child routing modules
    
        // Last module
        AppRoutingModule
      ],
      providers: [
        //..
      ],
      bootstrap: [
        //..
      ]
    })
    export class AppModule { }