【问题标题】:Angular 2 - Why imported module routing order is different to fix-coded?Angular 2 - 为什么导入的模块路由顺序与固定编码不同?
【发布时间】:2018-02-17 05:30:00
【问题描述】:

假设我的 app.module.ts 中有这个

@NgModule({
   imports: [
     BrowserModule,
     HttpModule,
     RouterModule.forRoot([
        {path: 'home', component: HomeComponent},
        {path: '', redirectTo: 'home', pathMatch: 'full'},
        {path: '**', component: NotFoundComponent},
     ]),
     UserModule
     ...
})

我认为这导致了这个路由顺序:

{路径:'用户',组件:用户组件},
{路径:'home',组件:HomeComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
{路径:'**',组件:NotFoundComponent}

请注意,用户现在在其他人之前。

现在我将 RouterModule.ForRoot 部分导出到另一个名为 AppRoutingModule 的模块。

@NgModule({
   imports: [
     BrowserModule,
     HttpModule,
     AppRoutingModule, // newly created routing module
     UserModule
     ...
})

在我看来,这导致了这一点:

{路径:'home',组件:HomeComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
{路径:'**',组件:NotFoundComponent},
{路径:'用户',组件:用户组件}

请注意,用户现在在其他人之后。

所以我必须将 AppRoutingModule 放在 UserModule 下方。为什么会这样实现?

【问题讨论】:

  • 用户路由在哪里以及如何定义的?

标签: angular angular2-routing


【解决方案1】:

以下是官方文档中的两个链接,可以帮助您了解如何进行导入,以及如何了解当前的订单路线:

App.Module.ts

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

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

App.Module.ts

// Diagnostic only: inspect router configuration
constructor(router: Router) {
  console.log('Routes: ', JSON.stringify(router.config, undefined, 2));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2020-02-23
    • 2017-01-07
    • 2020-06-08
    • 2015-10-29
    • 2017-02-28
    • 1970-01-01
    • 2018-12-26
    相关资源
    最近更新 更多