You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何通过Appointment对象的UserId关联获取并显示用户名称

问题原因

你现有代码的核心问题是把*ngFor="let user of users"放在了<mat-expansion-panel-header>节点上,会导致每个预约项循环生成和用户数组长度一致的头部块,完全不符合预期,同时模板里多写的星号、冗余的this关键字也会导致逻辑异常。

最优解决方案(推荐)

优先在组件TS层提前做数据映射,避免模板层做多余循环,性能更好逻辑也更清晰:

  1. 先在TS中拿到users和appointments数据后,生成用户ID到用户对象的映射表,再把对应用户信息挂载到预约对象上:
// 示例代码写在你获取到两个数组的逻辑之后
const userMap = new Map(this.users.map(user => [user.UserId, user]));
this.appointments = this.appointments.map(appointment => ({
  ...appointment,
  // 匹配不到用户的时候也给个默认值避免报错
  relatedUser: userMap.get(appointment.UserId) || { ContactId: '未知用户' }
}));
  1. 模板层直接取用挂载好的用户信息即可,修正后的模板代码如下:
<mat-accordion>
  <mat-expansion-panel class="content" *ngFor="let app of appointments; let i = index">
    <mat-expansion-panel-header>
      <mat-panel-title>Image: </mat-panel-title>
      <mat-panel-title>Client: {{app.relatedUser.ContactId}}</mat-panel-title>
      <mat-panel-title>Location: {{currentLocation}}</mat-panel-title>
      <mat-panel-title>Date: {{app.StartDate | date : 'MM-dd-yyyy'}}</mat-panel-title>
      <mat-panel-title>Time: {{app.StartDate | date : 'hh:mm'}}</mat-panel-title>
      <i class="material-icons-outlined" style="align-self: end">expand_more</i>
    </mat-expansion-panel-header>
    <mat-panel-description>
      <p>Desc: {{app.Description}}</p>
    </mat-panel-description>
  </mat-expansion-panel>
</mat-accordion>

临时解决方案(不推荐,仅快速验证用)

如果不想修改TS代码,也可以直接在模板里做查找,注意这种方式性能较差,仅适合小数据量场景:

<mat-accordion>
  <mat-expansion-panel class="content" *ngFor="let app of appointments; let i = index">
    <mat-expansion-panel-header>
      <mat-panel-title>Image: </mat-panel-title>
      <mat-panel-title>Client: {{users.find(u => u.UserId === app.UserId)?.ContactId || '未知用户'}}</mat-panel-title>
      <mat-panel-title>Location: {{currentLocation}}</mat-panel-title>
      <mat-panel-title>Date: {{app.StartDate | date : 'MM-dd-yyyy'}}</mat-panel-title>
      <mat-panel-title>Time: {{app.StartDate | date : 'hh:mm'}}</mat-panel-title>
      <i class="material-icons-outlined" style="align-self: end">expand_more</i>
    </mat-expansion-panel-header>
    <mat-panel-description>
      <p>Desc: {{app.Description}}</p>
    </mat-panel-description>
  </mat-expansion-panel>
</mat-accordion>

内容的提问来源于stack exchange,提问作者S-Grace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:09:02