Astrophage
Astrophage

Reputation: 1429

Angular 2 - Why imported module routing order is different to fix-coded?

Let's say i'have this in my app.module.ts

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

this leads in my opinion to this routing order:

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

Note that User is now before the others.

Now i am exporting the part RouterModule.ForRoot to another module called AppRoutingModule.

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

this leads now to this in my opinion:

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

Note that User is now after the others.

So i have to put the AppRoutingModule below the UserModule. Why is it implemented like this?

Upvotes: 4

Views: 2520

Answers (1)

Alex Beugnet
Alex Beugnet

Reputation: 4071

Here are two links from the official documentation that will help you understand how imports are made, and how to know the current order route :

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 { }

The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.

App.Module.ts

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

Upvotes: 2

Related Questions