George Edwards George Edwards - 3 months ago 510
TypeScript Question

Angular2 Module cannot match component child routes

So I have an angular2 based web app. The site has a submodule called tutorial with its own sub-router (to navigate through the "chapters"). So here is my app.

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


So when I go to
/tutorial
, then that's fine, I get a list of all my chapters and their links, however, when I click a link e.g.
href="/tutorial/chapter/1"
from the tutorial I get the error:


Error: Uncaught (in promise): Error: Cannot match any routes: 'chapter/1'


I also tried setting the links as
tutorial/chapter
but I still got the same result. What have I done wrong?

Update:



If you want to see the full project, here is a link to the relevant part of my full project repo.

Answer

It seems you set wrong path. Change this line:

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

Into this:

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

Also, in root routes table (app.routes.ts) you have to add followed line:

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

To show angular, where it should try to find your child module. Check this example: http://angularjs.blogspot.com/2016/08/angular-2-rc5-ngmodules-lazy-loading.html

Comments