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

Angular对象嵌套匹配及TypeScript报错解决:根据emailAddress匹配selectedNewUser与res.items并获取对应roles

解决TypeScript错误并实现邮箱匹配获取角色的需求

错误原因分析

你遇到的Property 'roles' does not exist on type 'any[]'错误很明确:this.selectedNewUser是一个数组,而不是单个用户对象,数组本身并没有roles属性。你直接写this.selectedNewUser.roles相当于在数组上找不存在的属性,自然会报错。

我们需要先从selectedNewUser数组中找到与当前res.items里的item邮箱匹配的用户对象,再去访问这个对象的roles属性。

解决方案步骤

1. (可选但推荐)定义类型,避免any类型隐患

为了让TypeScript更好地做类型检查,我们可以给selectedNewUser里的用户对象定义一个接口:

interface SelectedUser {
  emailAddress: string;
  firstName: string;
  lastName: string;
  phoneNumber: string;
  companyName: string;
  title: string;
  roleId: number;
  associatedAccount: string;
  accountId: number;
  roles: Array<{
    id: number;
    name: string;
    isShow: boolean;
    transactionRoleId: number;
  }>;
}

// 给selectedNewUser指定类型,替代any[]
selectedNewUser: SelectedUser[] = [];

2. 修改核心逻辑,正确获取匹配用户的roles

在你的subscribe的next回调里,把错误的this.selectedNewUser.roles改成通过find方法找到匹配的用户后再取roles:

修改后的完整代码片段:

private _transactionUserPageEvent() {
  this.isTransactionUserLoading = true;
  this.transactionUserTable.data = [];
  this._userProfileService.getTeamProfileTableDropdown(
    this.accountId,
    this.transactionUserTable.pageIndex + 1,
    this.transactionUserTable.pageSize,
    this.searchTransactionUserInput.nativeElement.value,
    this.transactionUserTable.sortParams,
    this.transactionUserTable.sortDirs
  )
  .pipe(
    finalize(() => this.isTransactionUserLoading = false)
  )
  .subscribe({
    error: err => this._notificationService.showError(err),
    next: res => {
      this.transactionUserTable.totalElements = res.totalItemCount;
      this.transactionUserTable.data = res.items as unknown as UserProfileDropdownDto[];
      this.totalData = res.totalItemCount;
      this.currentDisplayedData = res.lastItemOnPage;
      console.log("res" , res.items)
      if(this.selectedNewUser.length !== 0) {
        res.items.forEach(item => {
          if(item.emailAddress) {
            // 找到selectedNewUser中邮箱匹配的用户
            const matchedUser = this.selectedNewUser.find(x => x.emailAddress === item.emailAddress);
            if(matchedUser) {
              item.isChecked = true;
              this.userSelectedStatus(item);
              this.appendUserList(true,item);
              // 使用匹配到的用户的roles
              this.transactionRoleEvent(matchedUser.roles, item.id);
              // 打印验证结果
              console.log(`匹配到用户${item.emailAddress}的roles:`, matchedUser.roles);
            }
          }
        });
      }
    },
    complete: noop
  });
}

关键改动说明

  • 用find方法替代findIndex,直接获取到匹配的用户对象matchedUser
  • 只有当matchedUser存在(即找到匹配项)时,才执行后续逻辑并访问matchedUser.roles
  • 这样既解决了TypeScript的类型错误,也准确实现了“根据邮箱匹配获取对应roles”的需求

内容的提问来源于stack exchange,提问作者user16619763

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:17:44