2016-12-24 50 views
2

我想了解Angular2中的路線。 This是這個鏈接。 我的問題是它找不到\heroes\hero\:id路由,它是在heroes-routing-module中創建的。每次加載主頁(\ heroes)時,都會顯示page not found文本,該文本來自頁面未找到頁面{ path: '**', PageNotFoundComponent}。以下是相關文件的摘錄(不是帶有導入和導出行的完整代碼)。Angular2無法找到功能模塊路線

英雄路由模塊

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

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

英雄模塊

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

APP模塊

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

應用路線

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

我已經檢查了所有的文件名進口的錯字,所以我排除加在這裏。控制檯中沒有錯誤,我正在使用Angular 2.1。 如果需要其他信息,請發表評論。

+0

嘗試在* App模塊*中將'RouterModule'添加到'imports'並將其導入到上面 –

回答

6

那是因爲你app.module進口是這樣的:

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

所以使用AppRoutingModule作爲最後的路由模塊:

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

進口秩序事情,當談到路由,angular2路由系統從上到下。

相關問題