Angular2模块无法匹配组件子路由

时间:2016-08-11 11:47:45

标签: angular typescript angular2-routing

所以我有一个基于angular2的网络应用程序。该站点有一个名为tutorial的子模块,它有自己的子路由器(用于浏览"章节")。所以这是我的应用程序。

tutorial.module.ts:

import { tutorialRouting } from './tutorial.routes';
import { tutorialComponent } from './tutorial.component';
import { chapterComponent } from './chapter/chapter.component';

@NgModule({
  imports: [
    CommonModule,
    tutorialRouting
  ],
  declarations: [
    tutorialComponent,
    chapterComponent
  ],
  providers: []
})
export class tutorialModule {}

tutorial.routes.ts:

import { tutorialComponent }    from './tutorial.component';
import { chapterComponent }  from './chapter/chapter.component';

const tutorialRoutes: Routes = [
  {
    path: 'tutorial',
    component: tutorialComponent,
    children: [
      { path: '/chapter/:id',  component: chapterComponent },
      { path: '', component: chapterComponent }
    ]
  }
];

export const tutorialRouting = RouterModule.forChild(tutorialRoutes);

tutorial.component.ts:

@Component({
  selector: 'tutorial',
  template: `
  <div class="content row">
    <div class="chapters col s3">
        <h3>Chapters:</h3>
        <a *ngFor="let chapter of chapters; let i=index" (click)="clickedItem = i" [class.clicked]="i == clickedItem" class="chapter" [routerLink]="['/chapter', chapter.number]">{{chapter.number}}. {{chapter.title}} </a>
    </div>
    <div class="col s9">
        <h1>Tutorial</h1>
        <router-outlet></router-outlet>
    </div>
  </div>`,
  styleUrls: ['app/tutorial/tutorial.css'],
  directives: [codeStepComponent, ROUTER_DIRECTIVES]
})
export class tutorialComponent {
    public chapters = _chapters; //this is an imported 
    clickedItem: number = 0;
 }

所以,当我转到/tutorial时,那很好,我会得到所有章节及其链接的列表,但是,当我点击链接时,例如从教程href="/tutorial/chapter/1"我得到错误:

  

错误:未捕获(在承诺中):错误:无法匹配任何路线:&#39; chapter / 1&#39;

我也尝试将链接设置为tutorial/chapter,但我仍然得到相同的结果。我做错了什么?

更新

如果您想查看整个项目,here是指向我的完整项目回购的相关部分的链接。

1 个答案:

答案 0 :(得分:1)

似乎你设置了错误的道路。改变这一行:

  { path: '/chapter/:id',  component: chapterComponent },

进入这个:

  { path: 'chapter/:id',  component: chapterComponent },

此外,在根路由表(app.routes.ts)中,您必须添加以下行:

  { path: 'tutorial', loadChildren: 'tutorial/tutorial.module', pathMatch: 'prefix'}

要显示角度,它应该尝试找到您的子模块。请查看此示例:http://angularjs.blogspot.com/2016/08/angular-2-rc5-ngmodules-lazy-loading.html