首页 文章

Angular 2 - 为什么导入的模块路由顺序与固定编码不同?

提问于
浏览
1

让我说我的app.module.ts中有这个

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

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

{path:'User',component:UserComponent},{path:'home',component:HomeComponent},{path:'',redirectTo:'home',pathMatch:'full'},{path:'** ',组件:NotFoundComponent}

请注意,User现在先于其他用户 .

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

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

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

{path:'home',component:HomeComponent},{path:'',redirectTo:'home',pathMatch:'full'},{path:'**',component:NotFoundComponent},{path:'User ',组件:UserComponent}

请注意,用户现在已经完成了其他用户 .

所以我必须将AppRoutingModule放在UserModule下面 . 为什么这样实现?

1 回答

  • 2

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

    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));
    }
    

相关问题