【问题标题】:Error: Cannot match any routes, URL segment undefined错误:无法匹配任何路由,URL 段未定义
【发布时间】:2018-02-07 09:25:36
【问题描述】:

我有一个父组件作为项目列表TokenData,URL 段为locahost:4200/tokens,当我单击列表的每一行时,它应该导航到一个子组件作为每个项目的详细信息。子组件的 URL 段应该是这种形式 tokens/:id 但错误显示为 tokens/undefined。我错在哪里以及如何将列表中项目的每个 id 正确传递到参数中?

这是我的代码:

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>

【问题讨论】:

  • 你访问的路径是什么?
  • 我从localhost:4200/tokens 访问,我希望当我点击表格行时,例如亚航,我可以转localhost:4200/tokens/airasia,参数应该是亚航的id
  • 路径:':id',而不是'tokens/:id'

标签: angular parameters angular-route-segment


【解决方案1】:

使用您的路线配置,您需要像locahost:4200/tokens/tokens/25 这样的路径

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

我猜你想要的是什么

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

【讨论】:

  • 我按照您的建议进行了更改,控制台日志中不再出现错误,但浏览器上的 URL 直到 tokens/undefined。所以我在ngOnInit里面的函数有问题?
  • 我想是的。如果您在ngOnInit 末尾执行console.log(this.tokens),应该很容易测试
  • 如果为每个令牌分配相同的 id,为什么还要这样做?你可以只做this.id = this.route.snapshot.params['id'];[routerLink]="['/tokens/', id]" (除非你在组件之外的某个地方也需要token.id
  • 糟糕,现在ngOninit 中的所有id 都未定义。我不明白为什么:(
  • 很难从可用信息中分辨出来。也许您可以使用stackblitz.com 创建一个最小的复制?
猜你喜欢
  • 2019-06-16
  • 2017-11-13
  • 1970-01-01
  • 2019-10-14
  • 2017-09-25
  • 2019-05-11
  • 2021-05-30
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多