user13531843
user13531843

Reputation:

subscribing two observables i.e. observable inside another observable HTTP

I am new to angular. I am trying to post and get data at a time. I am using map and subscribing the observable while the outer observable is subscribed in component.

add(data) {
  return this.postModel(`pathHere`, data)
  .pipe(map((resp) => {
    if(resp.models){
      return this.getRoomById(resp.models.id).subscribe();
    }
  }));
    }

Upvotes: 3

Views: 55

Answers (2)

andsilver
andsilver

Reputation: 5972

add(data) {
    return this.postModel(`pathHere`, data)
        .pipe(
            switchMap((resp) => {
                if (resp.models) {
                    return this.getRoomById(resp.models.id);
                }
                  return of(resp.models);
            })
        );
}

You can use switchMap to emit another Observable.

As you used if statement for checking resp.models, you have to handle the case when resp.models is not truthy.

Upvotes: 1

Analyst
Analyst

Reputation: 911

I guess you need to use flatMap instead of map as

add(data) {
  return this.postModel(`pathHere`, data)
  .pipe(flatMap((resp) => {
    if(resp.models){
      return this.getRoomById(resp.models.id);
    }
  }));
    }

Upvotes: 1

Related Questions