AngularM
AngularM

Reputation: 16648

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);
});

Upvotes: 4

Views: 1825

Answers (3)

alex kucksdorf
alex kucksdorf

Reputation: 2633

Try using .flatMap() instead:

this.serviceA.getOrg()
    .flatMap((org) => this.serviceB.getOrgType(org.id))
    .subscribe((type) => {
        console.log(type);
});

Upvotes: 2

Chandru
Chandru

Reputation: 11192

try like this :

this.serviceA.getOrg()
    .flatMap((org) => {
        console.log('org', org);
        return this.serviceB.getOrgType(org.id)
    })
    .subscribe((type) => {
        console.log('type', type);
    });

Upvotes: 3

Faly
Faly

Reputation: 13356

Try flatMap:

 this.serviceA.getOrg()
    .flatMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type=> {
      console.log(type);
    });

Upvotes: 4

Related Questions