Sajan
Sajan

Reputation: 1923

Angular2 can't find feature module routes

I am trying to understand the routes in Angular2. This is the plunker link for that . My problem is it can't find the \heroes or \hero\:id route, which is created in heroes-routing-module. Every time the home page(\heroes) loads, it shows page not found text as which is coming from page not found page { path: '**', PageNotFoundComponent}. Below are excerpts(not full code which has import and export lines) of relevant files.

Heroes routing module

const heroesRoutes: Routes = [
  { path: 'heroes',  component: HeroesComponent },
  { path: 'hero/:id', component: HeroDetailComponent }
];

@NgModule({
  imports: [
    RouterModule.forChild(heroesRoutes)
  ],
  exports: [
    RouterModule
  ]
})

Heroes module

@NgModule({
  imports: [
    HeroRoutingModule,
    SharedModule
  ],
  declarations: [
    HeroesComponent,
    HeroDetailComponent,
    HeroSearchComponent
  ],
  providers: [
    HeroService
  ]
})

App module

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule,
    HeroesModule,
    SharedModule
  ],
  declarations: [
    AppComponent,
    DashboardComponent,
    CrisisListComponent,
    PageNotFoundComponent
  ],
  bootstrap: [ AppComponent ]
})

App route

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent }   from './dashboard.component';
import { CrisisListComponent }  from './crisis/crisis-list.component';
import { PageNotFoundComponent } from './not-found.component';

const routes: Routes = [
  { path: 'dashboard',  component: DashboardComponent },
  { path: 'crisis-center', component: CrisisListComponent },
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

I have checked all file names in import for typo so I excluded from adding here. There is no error in console and I am using Angular 2.1. Please comment if any other info needed.

Upvotes: 2

Views: 1145

Answers (1)

eko
eko

Reputation: 40647

That is because your app.module imports are like this:

  imports: [
    BrowserModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule, //<-- after this it won't be finding the routes below because of the wildcard route
    HeroesModule,
    SharedModule
  ]

So use the AppRoutingModule as the last routing module:

  imports: [
    BrowserModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    HeroesModule,
    AppRoutingModule,
    SharedModule
  ]

Order of imports matter when it comes to routing, angular2 routing system goes from top to bottom.

Upvotes: 12

Related Questions