【问题标题】:Angular wildcard route replacing child routesAngular 通配符路由替换子路由
【发布时间】:2019-10-17 10:47:58
【问题描述】:

我有一个名为“host”的模块,它有自己的路由,我想将它插入到 app-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>

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

【问题讨论】:

  • 预期结果?我没有看到您有“主机”的路由路径,或者它是延迟加载的。
  • @penleychan 请在原始问题中查看我的更新。在 app.component.html 中有 Host 的 routerLink
  • 再次,HostModule 的使用/定义位置和方式。如果您只是将模块导入AppModule,则需要管理您的导入顺序。配置中路由的顺序很重要,这是设计使然。
  • @penleychan 哦,我想我明白你在问什么。我更新了 app.module.ts 文件。请看

标签: javascript angular single-page-application angular7 angular7-router


【解决方案1】:

在您的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 - Not Found”页面或重定向到另一个路由很有用。

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

【讨论】:

  • 这是 Angular 7 中的新功能吗?我不记得其他版本是这样的。谢谢你的回答
  • @user1142130 不,很确定一直都是这样,也许之前你在做延迟加载?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2017-05-18
  • 1970-01-01
  • 2016-10-28
相关资源
最近更新 更多