1

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

主机模块.ts

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

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

应用程序路由.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>

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

在此处输入图像描述

4

1 回答 1

3

在你的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

最后一条路由中的 ** 路径是通配符。如果请求的 URL 与配置中先前定义的路由的任何路径都不匹配,路由器将选择此路由。这对于显示“404 - 未找到”页面或重定向到另一条路线很有用。

配置中路由的顺序很重要,这是设计使然。路由器在匹配路由时使用先匹配获胜策略,因此更具体的路由应该放在不太具体的路由之上。在上面的配置中,首先列出了具有静态路径的路由,然后是与默认路由匹配的空路径路由。通配符路由位于最后,因为它匹配每个 URL,并且只有在没有其他路由首先匹配时才应选择。

于 2019-05-31T21:34:30.627 回答