错误:无法匹配任何路由,URL段未定义

时间:2018-02-07 09:25:37

标签: angular parameters angular-route-segment

我有一个父组件作为项目列表TokenData,其网址段为locahost:4200/tokens,当我点击列表的每一行时,它应该导航到子组件作为每个项目的详细信息。子组件的网址段应采用此格式tokens/:id,但错误显示为tokens/undefined。我错在哪里以及如何正确地将列表中项目的每个id传递给params?

这是我的代码:

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>

1 个答案:

答案 0 :(得分:3)

使用您的路线配置,您需要一条像locahost:4200/tokens/tokens/25

这样的路径
{ path: 'tokens/:id', component: TokenDetailComponent }

我想你想要的是

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