Angular 通配符路由替换子路由

Angular wildcard route replacing child routes

我有一个名为 "host" 的模块,它有自己的路由,我想将其插入应用程序-routing.module。但是,我遇到通配符首先加载并显示 PageNotFoundComponent 而不是 Host 组件加载的问题。我有以下文件。

host.module.ts

....
const routes: Routes = [
  {
    path: 'host',
    children: [
     { path: '', component: HostComponent }
    ]
  }
];

@NgModule({
  declarations: [HostComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ]
})
export class HostModule { }

app-routing.module.ts

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: "full"},
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HostModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<h2>Home</h2>
<ul>
  <li>
    <h2><a routerLink="/host">host</a></h2>
  </li>
</ul>
<router-outlet></router-outlet>

问题: 当我 运行 应用程序并单击 "Host" 按钮时,它会加载 PageNotFoundComponent。我显然希望它转到 HostComponent。

在您的 app.module.ts 中,您需要重新订购您的进口商品

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    HostModule, <--- this before AppRoutingModule
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

原因是配置中路由的顺序很重要。 https://angular.io/guide/router#configuration

The ** path in the last route is a wildcard. The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.

The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.