【发布时间】:2021-07-17 12:48:57
【问题描述】:
我有一个device_ids 数组。该数组通过在 UI 上选择项目来动态扩展。
最初,无论何时更新数组,我都需要遍历它并为每个device_id 获取数据。 G
获取数据基本上是一个返回 Observable 的数据库请求(对 Firestore)。通过使用switchMap,我从其他数据库请求中获取了一些数据。
最后,我想要一个对象数组/ Observables 之类的东西,其中包含我可以订阅的所有数据。我的目标是在我的 HTML 中使用 Angular 的异步管道。
这可能吗(例如使用 RxJS)?我不知道如何解决这个问题......
这是我的代码目前的样子:
// Init
devices$: Observable<any;
// Array of device_ids
device_ids = ['a', 'b'];
// Get device data. This will initially be called on page load.
getDeviceItemData(device_ids) {
// Map / loop device_ids
device_items.map(device_id => {
// getDeviceById() returns an Observable
return this.getDeviceById(device_id).pipe(
// Switch to request additional information like place and test_standard data
switchMap(device => {
const place$ = this.getPlaceById(device['place_id]');
const test_standard$ = this.getTestStandardById(device['test_standard_id]');
// Request all data at the same time and combine results via pipe()
return zip(place$, test_standard$)
.pipe(map(([place, test_standard]) => ({ device, place, test_standard })));
})
).subscribe(device_data => {
// Do I need to subscribe here?
// How to push device_data to my Observable devices$?
// Is using an Observable the right thing?
});
});
}
// Add device
addDevice(device_id) {
// Add device_id to array
this.device_ids.push(device_id);
// Fetch data for changed device_ids array
getDeviceItemData(this.device_ids);
}
使用异步管道的首选 HTML / Angular 代码:
<div *ngFor="device of devices$ | async">{{ device.name }}</div>
感谢您的帮助!
【问题讨论】:
标签: arrays angular rxjs observable