hope you can help me out.
I have a function called getEnergyFromPower which returns a string of values:
getEnergyFromPower(systemId: number, objectId?: string) {
...
return this.httpClient.get(this.BASE_URL + this.AGGREGATE_URL, {
headers: this.BEARER_OPTIONS.headers,
responseType: 'text',
params: params
})
}
And another one that was supposed to loop through the values of an Observable. But when I subscribe and console.log it it returns instead an array of observables like so:
organizeEnergy(systemId: number = 49439) {
return this.getSystemLayout(systemId).pipe(
map(res => {
return res.map(({object_id}) => this.getEnergyFromPower(49439, object_id))
})
)
}
this.optService.organizeEnergy().subscribe(res => console.log(res))
// Returns:
// [Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable]
I tested to see if the object_id was right and it returns the right values like so:
organizeEnergy(systemId: number = 49439) {
return this.getSystemLayout(systemId).pipe(
map(res => {
return res.map(({object_id}) => object_id)
})
)
}
this.optService.organizeEnergy().subscribe(res => console.log(res))
//RETURNS
// (8) [83978300, 83978301, 83978302, 83978303, 83978304, 83978305, 83978306, 83978307]
I also tested it hard coded like so and it works:
organizeEnergy(systemId: number = 49439) {
return this.getEnergyFromPower(systemId, '83978300')
}
this.optService.organizeEnergy().subscribe(res => console.log(res))
//RETURNS
// 2021/07/13 08:55:00.000,38
So I'm guessing my problem is when I try to map the response in this line:
organizeEnergy(systemId: number = 49439) {
...
return res.map(({object_id}) => this.getEnergyFromPower(49439, object_id))
...
}
So I would like to loop through it and dynamically the results whenever I subscribe to it.
Maybe it's something I didn't yet grasp since it's been two weeks I started with Angular/Observables/HttpClient
I think you need to use a combination of switchMap
and combineLatest
.
import { combineLatest } form 'rxjs';
import { switchMap } from 'rxjs/operators';
organizeEnergy(systemId: number = 49439) {
return this.getSystemLayout(systemId).pipe(
// change map to switchMap because we are going to switch to a new observable
switchMap(res => {
// combine all HTTP requests and return the results as an array
return combineLatest(...res.map(({object_id}) => this.getEnergyFromPower(49439, object_id)));
}),
)
}
// This should give you [2021/07/13 08:55:00.000,38, ...]
this.optService.organizeEnergy().subscribe(res => console.log(res))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With