Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to use result of `.subscribe()` in consequent Observable

Angular2: I want to use the result of .subscribe() in a consequent observable.

This is in order to use the id from the parent subscribe in the nested subscribe.

I've tried using .switchMap() first, but this doesn't seem to work.

This is my attempt:

this.serviceA.getOrg()
    .switchMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type => {
        console.log(type);
});
like image 381
AngularM Avatar asked Jan 03 '23 04:01

AngularM


2 Answers

Try flatMap:

 this.serviceA.getOrg()
    .flatMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type=> {
      console.log(type);
    });
like image 176
Faly Avatar answered Jan 05 '23 17:01

Faly


try like this :

this.serviceA.getOrg()
    .flatMap((org) => {
        console.log('org', org);
        return this.serviceB.getOrgType(org.id)
    })
    .subscribe((type) => {
        console.log('type', type);
    });
like image 22
Chandru Avatar answered Jan 05 '23 17:01

Chandru