Angular2 找不到功能模块路由



我试图理解Angular2中的路线。这是为此的链接。我的问题是找不到在heroes-routing-module中创建的heroeshero:id路由。每次主页( Heroes)加载时,都会显示page not found文本,其中来自页面未找到页面{ path: '**', PageNotFoundComponent}。以下是相关文件的摘录(不是具有导入和导出行的完整代码)。

英雄路由模块

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

应用模块

@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。如果需要任何其他信息,请发表评论。

那是因为您的 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路由系统从上到下。

最新更新