Error: Cannot match any routes, URL segment undefined

Hoàng Nguyễn picture Hoàng Nguyễn · Feb 7, 2018 · Viewed 7k times · Source

I have a parent component as a list of items TokenData with URL segment as locahost:4200/tokens, when I click each row of the list, it should navigate to a child component as each item's detail. The URL segment of the child component should be in this form tokens/:id but the error showed up as tokens/undefined. Where was I wrong and how to pass each id of item in the list into the params properly?

Here is my code:

app.module.ts:

RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'tokens', component: TokensComponent,
        children: [
          { path: 'tokens/:id', component: TokenDetailComponent }
        ]
      }
    ])

tokens.component.ts:

export class TokensComponent implements OnInit {
  displayedColumns = ['logo', 'token name', 'industry'];
  dataSource: MatTableDataSource<TokenData>;

  tokens: TokenData[] = [
    { id: 'airasia', tokenName: 'Air Asia', industry: 'Airline Service' },
    { id: 'airbaltic', tokenName: 'Air Baltic', industry: 'Airline Service' },
    { id: 'airitalia', tokenName: 'Air Italia', industry: 'Airline Service' }
  ];

  constructor(private route: ActivatedRoute) {
    this.dataSource = new MatTableDataSource(this.tokens);
  }

  ngOnInit() {
    for (const i of this.tokens) {
      i.id = this.route.snapshot.params['id'];
    }
  }
}

tokens.component.html:

<mat-table [dataSource]="dataSource" matSort>              
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;" [routerLink]="['/tokens/', row.id]">
    </mat-row>

    <ng-container matColumnDef="token name">
      <mat-header-cell *matHeaderCellDef mat-sort-header> TOKEN NAME </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.tokenName}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="industry">
      <mat-header-cell *matHeaderCellDef mat-sort-header> INDUSTRY </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]=""> {{row.industry}} </mat-cell>
    </ng-container>
  </mat-table>

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Feb 7, 2018

With your route configurations you would need a path like locahost:4200/tokens/tokens/25

{ path: 'tokens/:id', component: TokenDetailComponent }

I guess what you want is

{ path: ':id', component: TokenDetailComponent }