【问题标题】:Angular 2 route with parameter acts as wildcard route带参数的 Angular 2 路由充当通配符路由
【发布时间】:2018-05-13 20:28:42
【问题描述】:

我有一个带有多个模块的 Angular 应用程序,每个模块都定义了一些路由。

应用(基本模块)使用此 AppRoutingModule:

const routes: Routes = [
  {path: 'user', loadChildren: 'app/user/user.module#UserModule'},
  {path: 'exchange', loadChildren: 'app/exchange/exchange.module#ExchangeModule'},
  {path: 'home', component: HomeComponent},
  {path: '', redirectTo: '/home', pathMatch: 'full'},
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

用户模块路由器:

@NgModule({
  imports: [RouterModule.forChild(
    [{
      path: '', component: UserComponent,
      children: [
        {path: '', component: UserProfileComponent, canActivate: [AuthGuardService]},
        {path: 'login', component: UserLoginComponent},
        {path: 'register', component: UserRegisterComponent},
        {path: 'confirm/:confirmcode', component: UserConfirmMailComponent},
        {path: 'logout', component: UserLogoutComponent}
      ]
    }]
  )],
  exports: [RouterModule]
})
export class UserRoutingModule {
}

交换模块路由器:

@NgModule({
  imports: [RouterModule.forChild(
    [{
      path: '', component: ExchangeComponent,
      children: [
        {path: '', component: ExchangeListComponent},
        {path: ':exchange-name', component: ExchangeDetailComponent},
        {path: ':exchange-name/:baseCode', component: ExchangeSelectionComponent},
        {path: ':exchange-name/:baseCode/:targetCode', component: ExchangePairComponent},
      ]
    }]
  )],
  exports: [RouterModule]
})
export class ExchangeRoutingModule {
}

我现在可以按预期使用路由http://localhost:4200/exchange/Sample/Base 访问ExchangeSelectionComponent 组件。

但是当我导航到http://localhost:4200/user/confirm/ 并且不小心错过了添加所需参数confirmcode 时,我匹配到了与上面相同的ExchangeSelectionComponent-route 而不是Invalid-Route-Error。 此外,当我尝试打开http://localhost:4200/thispagedoesnotexist 时,我会使用exchange-name = thispagedoesnotexist 进入ExchangeDetailComponent

似乎/exchange/ 下面的所有内容也与基本根/ 匹配。

为什么会这样,我该如何避免这种行为? 我认为在routeChildren 内部的路由中定义的每条路由只会在访问相应的父路由时才被延迟加载,直到那时甚至没有被触及。

我使用 Angular 5.2。提前感谢您的任何意见。

【问题讨论】:

  • 您的示例中的这一行不完整{path: 'exchange', loadChildren:'app/exchange/exchange.module# 能否请您正确写下,以便我们知道那里有什么。
  • 抱歉,已修复
  • np,你有没有在 app.module 中导入交换模块?
  • 是的,我有。我首先将它们添加为普通模块,然后对其进行更新以进行延迟加载。在从 AppModule 中删除导入后,该行为符合预期。谢谢!
  • 这是个好消息,是的,我会写这个作为答案,谢谢!

标签: angular angular-routing


【解决方案1】:

我猜测 ExchangeModule 是在 app.module 中导入的,因此它的路由定义正在被解析,而不是延迟加载的。

path: '', component: ExchangeComponent

确保模块是延迟加载的,并且没有在 app.module 中导入,这可以通过快速检查 app.module 文件或通过检查网络选项卡来确认,并在您访问应该是的路由时查找新加载的块延迟加载,如果一个新的块没有被加载,那么你的模块已经被导入 app.module 并且没有被延迟加载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2018-10-06
    • 2017-03-22
    • 2017-02-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多