如果有人能帮我,我有以下问题,我按项目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)
});
});
});
发布于 2021-07-01 22:34:51
简短答案:在调用API之前移动this.customersUsuarios
(如果它事先没有被分配为数组),如下所示
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)
Details:我们将data2
内部的数据直接分配给this.customersUsuarios
,因此,每当通过data2
获得新数据时,它就会替换以前API调用中数组中已经存在的数据。
所以,不要像这样分配它。在调用任何API之前,我们需要一个接一个地积累来自data2
内部的所有响应,首先是一个空数组(这是一个容器),然后通过将新的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);
这就是this.customersUsuarios
如何为每个API调用生成data2
内部的所有响应。
这个答案是基于我对此所能理解的(如果我错了,我也会设法解决)。
https://stackoverflow.com/questions/68214757
复制相似问题