简体   繁体   中英

Angular2 child routes

I have root module and a child module in angular2, both has its own routes defined. In child module am configuring RouterModule as

RouterModule.forChild(ROUTES)

In root module(parent) , am configuring RouterModule as

RouterModule.forRoot(ROUTES)

I am using same routes names in both child and root

In child

export const ROUTES: Routes = [
  { path: '',      component: HomeComponent }, //outputs I am child
  { path: 'home',  component: HomeComponent }
];

In root (parent)

export const ROUTES: Routes = [
  { path: '',      component: HomeComponent }, //outputs I am parent
  { path: 'home',  component: HomeComponent }
];

I am importing child module in root module

import .....
import {AppModule as ChildModule} from 'child-module/src/app/app.module';


@NgModule({
  bootstrap: [ AppComponent ],
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [ // import Angular's modules
    BrowserModule,
    FormsModule,
    HttpModule,
    ChildModule,
    RouterModule.forRoot(ROUTES, { useHash: true, preloadingStrategy: PreloadAllModules })

  ],
  providers: [
  ]
})
export class AppModule {

}

When I load my component (I mean root module), default route is always going to child module instead of rootmodule ie its printing "I am child" ,where as I expect "i am parent", child route should be loaded only when I load it, how can I route it to default route of root (parent) module instead of child module?

I think this answers your question:

Angular's router matches routes from the top down. The first route which matches is the one the router navigates to. You load the ChildModule 's routes before the RootModule 's routes, and that means those routes all have priority over the RootModule 's routes. When navigating to '' , the router will first check the ChildModule 's routes, find a match and take you there. If you swap the places of ChildModule and RootModule in the imports statement, then RootModule 's routes would always be navigated to.

You can learn more at https://angular.io/docs/ts/latest/guide/router.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM