-1

I have two observable called: callbacks and system.

I want to merge some data, so in my callback I have the property "systemId" and in my system I have the the property "name"

CallbackObservable:

this.callbacksService.toGetAllCallbacks().subscribe(callbacks => console.log(callbacks));

Result : One Array of object

[{...}]
0:
id: "555"
name: "teste 2 "
systemId: "123"

SystemObservable:

this.sistemaService.toGetSistemaById('123').subscribe(nome => console.log(nome));

Result: One Object

  {
    id: '123',
    name: 'teste',
   }

I want the result to be an array of callbacks with the id and name of the system like this:

{
id: "555"
name: "teste 2"
systemId: "123"
systemName: "teste"
}

So I tried using switchMap operator:

 this.callbacksService.toGetAllCallbacks().pipe(
      switchMap((element) => {
        return this.sistemaService.toGetSistemaById(element.systemId);
      })
    ).subscribe(data => {
      this.dado = data
      console.log(this.dado);
    });

It didn't work because on my second call to the service, it's sending 'undefined' and I don't know why.

enter image description here

Am I using switchmap in a wrong way?

Desenv Junior
  • 101
  • 1
  • 1
  • 10

1 Answers1

0

The first call this.callbacksService.toGetAllCallbacks() returns an array, so when you try to pass element.systemId this is undefined. So if i understood correctly you want to merge each array of the first call with the corresponding response from the second call. I dont know if this solution is the best, but it works:

this.callbacksService
  .toGetAllCallbacks()
  .pipe(
    mergeMap((data) => data),
    concatMap((element) => {
      return this.sistemaService.toGetSistemaById(element.systemId)
       .pipe(
        switchMap((elem) => {
          element.systemName = elem.name;
          return of(element);
        })
      );
    }),
    toArray()
  )
  .subscribe((data) => {
    this.dado = data;
    console.log(this.dado);
  });
tufonas
  • 303
  • 1
  • 7