angular - 从多个可观察值创建可观察值
问题描述
在我的一个组件中,我需要遍历一组 id 并为每个组件进行 API 调用。api 调用返回 observables,目前我只是订阅循环中的每一个并将其值添加到数组中。我不认为这很好,因为我正在单独订阅每个电话。有没有一种方法可以使用类似mergeMap
或类似的东西来创建循环中所有组合值的可观察值?
这样我就有了一个可以订阅(或使用 HTML 中的异步管道)而不是很多的 observable?
这是我的控制器代码:
export class GraphTablesComponent implements OnInit {
@Input() meta: any;
@Input() entityId: number;
kpiData: Array<any> = [];
constructor(
private apiService: ApiService
) { }
ngOnInit() {
this.getKpiData();
}
private getKpiData(): void {
for (const m of this.meta) {
this.apiService.post(`${Endpoints.KPIS}execute/${m._bid}/${this.entityId}`, {}).subscribe(d => this.kpiData.push(d));
}
}
}
解决方案
您可以使用ForkJoin来实现它
private getKpiData(): void {
let requestArray = [];
for (const m of this.meta) {
requestArray.push(this.apiService.post(`${Endpoints.KPIS}execute/${m._bid}/${this.entityId}`, {}))
}
forkJoin(requestArray).subscribe(data => {
this.response1 = data[0];
this.response2 = data[1];
});
}
如果您直接想在模板中添加它,
.ts
this.data$ = forkJoin(requestArray)
.html
<ng-container *ngIf="data$ | async; let data">
{{data | json}}
</ng-container>
推荐阅读
- c# - GetInstanceExtensions<> 方法中的工作流扩展 NULL
- string - Hive:删除字符串列中的空格
- sql - 需要获取日期时间范围之间的用户数
- julia - 有没有办法阻止 Julia 使用 BigFloats 的科学(指数)表示法?
- java - 过滤logstash输入
- python - 检索按值排序的值的索引的最pythonic方法是什么?
- php - 如何从保存在数据库中的文本中使用 php 中的 %variable% 等动态变量?
- javascript - Ajax调用好像缓存在IE11里,怎么每次都强制这个调用?
- java - 使用 https 时检票不正确的可收藏页面 url
- reactjs - 反应和 JavaScript