I have an array of device_ids. The array is extended dynamically by selecting items on a UI.
Initially and whenever the array is updated, I need to iterate through it and fetch data for each device_id. G
Getting data is basically a database request (to Firestore) which returns an Observable. By using switchMap I fetch some data from other database requests.
In the end I'd like to have something like an array of objects / Observables with all data I can subscribe to. My goal is using Angular's async pipe in my HTML then.
Is that possible (e.g. with RxJS)? I'm not sure how to solve this...
This is how my code currently looks like:
// 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);
}
Preferred HTML / Angular code by using async pipe:
<div *ngFor="device of devices$ | async">{{ device.name }}</div>
Thank you for any help!