首页 > 解决方案 > 数据没有被它的 id 分隔,最后到达的数据正在替换一切

问题描述

如果有人可以帮助我,我有以下问题,我按项目 ID 带来了用户列表,问题是当我带来它时,它总是抛出最后一个选项,而不是我所在的选项,所有值来自id的每个选项,但如果有人可以帮助我,最后到达的总是会粉碎另一个选项

        <mat-form-field class="flex-auto">
            <mat-label>MIEMBROS</mat-label>
            <mat-select formControlName="userId" #labelSelect="matSelect" multiple>

                <mat-option (click)="createCustomer()" *ngFor="let user of customersUsuarios;" [value]="user.id">
                    {{ user.nombres }} {{ user.apellidos}}
                </mat-option>
            </mat-select>

        </mat-form-field>

        <mat-form-field class="sm:ml-6 flex-auto" style="display: none;">
            <mat-label>ID DEL PROYECTO</mat-label>
            <input formControlName="projectId" disabled readonly [(ngModel)]="defaults.id" matInput>
        </mat-form-field>
    </div>

TS

        this.API.getProjects()
  .subscribe((data: CustomerProyecto[]) => {
    this.customersProyecto = data;
    data.forEach((element, i) => {
      this.API.getDataUsuariosNoRegistrados(element.id)

        .subscribe((data2: any) => {

          this.customersUsuarios = data2
          console.log("id del elemento ", element.id)

          console.log("datos de los usuarios ", data2)

        });
    });


  });

在此处输入图像描述

标签: angular

解决方案


简短答案this.customersUsuarios在调用 API 之前移动(如果它没有预先分配为数组)像这样

this.customersUsuarios = []
this.API.getDataUsuariosNoRegistrados(element.id)
...

而不是data2直接分配给this.customersUsuarios,而是将数据推送到数组中(考虑data2到作为数组出现)

// this.customersUsuarios = data2

// pushing data from `data2` inside array of `customersUsuarios`
// so, all the data can be collected instead of the last one only
this.customersUsuarios.push(...data2)

详细信息:我们将data2直接传入的数据分配给this.customersUsuariosso,每当新数据通过data2它时,它都会替换先前 API 调用中已经存在于数组中的数据

所以,而不是像这样分配它。我们需要data2一个一个地累积所有的响应,在调用任何 API 之前从一个空数组(认为这是一个容器)开始,然后通过将新的推data2送到每个元素的数组中来组合/合并响应(合并内容已经在容器内,每个元素都有一个新的)

您可以使用下面给出的任何合并技术示例

// As mentioned previously, it adds the data directly into `this.customersUsuarios`
this.customersUsuarios.push(...data2)

/** 
 * OR 
 * 
 * concat two arrays (just like old days)
 * here we are assigning it because `concat` returns 
 * a new merged array and does not alter the array in question
 */
this.customersUsuarios = this.customersUsuarios.concat(data2)

// Another concat approach, same reason whichever you find easy to reason about
this.customersUsuarios = [].concat(this.customersUsuarios, data2);

这就是为每个 API 调用this.customersUsuarios生成所有响应的方式data2

这个答案是基于我能从中理解的(如果我在这里错了,请告诉我,我也会尝试解决这个问题)


推荐阅读