angular - 数据没有被它的 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)
});
});
});
解决方案
简短答案: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.customersUsuarios
so,每当新数据通过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
这个答案是基于我能从中理解的(如果我在这里错了,请告诉我,我也会尝试解决这个问题)
推荐阅读
- javascript - 为什么我用来显示/隐藏 div 的 javascript 在 IE 中不起作用?
- html - 响应式配置器的问题
- kubernetes - Kubernetes Service ping 不时工作“名称解析暂时失败”
- bash - 获取子网 ID AWS
- r - 枢轴加宽表 dyplr R
- intel - mem_load_uops_retired.l3_miss 和 offcore_response.demand_data_rd.l3_miss.local_dram 事件之间的区别
- javascript - fullcalendar 通过悬停在当天添加工具提示
- bash - 在 Bash 中按大小和修改时间列出目录
- javascript - Nodejs流行为,未调用管道回调
- javascript - 如何在不通过折线图上的点的情况下构建垂直线?(图表.js)