Home > database >  How to combine two observable one after other?
How to combine two observable one after other?

Time:12-07

I have an Observable:

this.data$ = this.dataService.toGetAllData();

if I subscribe into this Observable, it will return this object:

this.dataService.toGetAllData().subscribe(response => console.log(response));

{
   id: "1"
   name: "test"
   systemId: "61a92ad360863a5a0346eca1"
}

So, I need to combine to another call to another service to return the name of the system according to the ID.

this.system$ = this.systemService.getSystemById(id);

How to combine this two observable into my variable data and return something like this:

{
       id: "1",
       name: "test",
       systemId: "61a92ad360863a5a0346eca1",
       systemName:" System Test"
    }

CodePudding user response:

Use switchMap:

import { switchMap } from "rxjs/operators";

this.system$ = this.dataService.toGetAllData().pipe(
  switchMap(data => this.systemService.getSystemById(data.id))
);

// then this.system$.subscribe(...) or whatever you need

CodePudding user response:

this.dataService.toGetAllData().subscribe(response => {
     console.log(response));
     this.system$ = this.systemService.getSystemById(response.id)
       .subscribe(result => {
          // here you will have a result with system name 
       }
}

CodePudding user response:

As you have updated your problem, you need to use mergeMap instead of switchMap

`
       this.system$ = this.dataService.toGetAllData().pipe(
        mergeMap(data => this.systemService.getSystemById(data.id).pipe(
            map((res) => data.systemName = res)
        ))
    );

    // then this.system$.subscribe(...) 

`

CodePudding user response:

systemdata : any

this.dataService.toGetAllData().subscribe(response => {
     this.systemdata = response;
     );  
}

this.system = this.systemService.getSystemById(systemdata.id)
       .subscribe(result => {
          // here you will have a result with system name 
       }
       
ngDestroy(){
//Since You are storing the subscribe value
this.system.unsubscibe()
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related