Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping through an observable and return values of nested observable

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

like image 781
Yuri Rech Avatar asked Jul 13 '21 17:07

Yuri Rech


1 Answers

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))
like image 192
AliF50 Avatar answered Nov 02 '22 12:11

AliF50