angular - 即使使用异步调用,我如何保持我的数组值?
问题描述
我有一个为每个类别画线的函数,在每一行中,我的函数必须放置一些点,每个点代表该类别的一个成员。
对于每个家庭成员,我将它们放在一个数组中。为了将它们放入数组中,我进行了 3 次查询(获取成员的所有信息,使用 API 在我的数据库的某个表中检索),并使用 rxjs 中的 zip 运算符将这些查询的结果放入数组中和管他们。
即使我不在 foreach 循环中,如何保持我的数组值?
ngOnInit(): void {
this.serviceData.currentService.subscribe(service =>
this.serviceFam.getAllFamilles().pipe(
switchMap(familles => // switchMap to switch into new observable
forkJoin( // forkJoin to run observables in parrallel
// map families to observables and run these calls in parallel
familles.map(f => forkJoin(
this.serviceAffecter.getAffecterServiceFamille(service, f.nom),
this.serviceOpe.getOperationsServiceFamille(service, f.nom)
).pipe( // gather them all up
map(([listAffecter, listeOperations]) => [f, listAffecter, listeOperations])
)
)
)
)
).subscribe((data: [Famille, Affecter, Operation][]) => {
// now that your observables are done, do the rest.
this.familles = data.map(d => d[0]);
for (let d of data) {
const f = d[0];
// why are these overwritten at every loop?
this.listeAffecter = d[1];
this.listeOperations = d[2];
//Here is my foreach loop where I put the info of all my members
for (let a of this.listeAffecter) {
var accessoire$ = this.serviceAccessoire.getAccessoireByIdAffaire(a.idAffaire);
var variante$ = this.serviceVar.getVarianteByIdAffaire(a.idAffaire);
var affaire$ = this.serviceAffaire.getAffaireById(a.idAffaire);
//Here is where I use zip to put the info in the array
var combined$ = zip(accessoire$, variante$.pipe(), affaire$.pipe());
combined$.subscribe(val =>
this.points.push({
"value": this.getTAT(a.dateEntree),
"name": val[0].nom + " " + f.nom +
" " + val[1].nom + " " + val[2].sn,
"operateur": "PERSONNE",
"affaire": a.id
})
);
}
//And this is where I want my data to be keeped
this.element = document.getElementById(f.nom) as HTMLElement;
this.element.innerText = "";
this.draw("#" + f.nom, this.points, {dateDimension: false, color: "teal", labelFormat: "%Y"});
this.points.length = 0;
this.operation.length = 0;
}
}),
err => {
console.log(err);
});
this.serviceData.changeAffaire(4);
}
如果有人对如何做到这一点有想法,那就太酷了。
解决方案
如果您在订阅中订阅了,那么您肯定使用 RxJS 错误。相反,您应该构建一个管道来修改通过它传递的值,直到您发出一个包含您需要的所有数据的结果。您如何将您的更改.subscribe
为更像这样的东西:
.pipe(switchMap((data: [Famille, Affecter, Operation][]) => {
return forkJoin(data.map((f,as,o) => {
return forkJoin(as.map(a => {
// Create your combined$ here using zip.
return combined$;
}));
}));
})).subscribe(vals => {
// Here vals is an array of arrays because of the nested forkJoin.
this.points = vals.flat().map(val => {
// Here you transform a value to a point.
});
this.draw(...);
});
推荐阅读
- javascript - 如何将道具发送到点击处理程序 - React JS
- ios - 快速在表格视图中添加滑动按钮
- javascript - 使用画布连接具有相同类的元素
- spring - Spring在类路径中找不到文件,但它就在war文件的根目录下
- java - tink 库 com.google.protobuf.GeneratedMessageV3$ 无法解析
- php - 如何判断 .php 文档中文件的路径?
- java - 是否可以将类(在 diff 模块中)添加到类路径并将其与反射一起使用
- java - 如何使用没有屏幕的java机器人模拟鼠标点击
- grafana - tidb grafana 没有数据点
- java - 使用 AWS4Signer 签署获取请求:我们计算的请求签名与您提供的签名不匹配