Search code examples
rxjsobservableangular-http

How to map http request observable result to new http observable and return both outer and inner values?


I would like to returns an observable that return two values (in an array or dict) where one value is a conditional http request of the first.

Taking the example from https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs, I would like to modify the following:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  homeworld: Observable<{}>;
  constructor(private http: Http) { }

  ngOnInit() {
    this.homeworld = this.http.get('/api/people/1')
      .map(res => res.json())
      .mergeMap(character => this.http.get(character.homeworld))
  }
}

So the observable will return both the homeworld and(!) the character.


Solution

  • Use can use resultSelector function of switchMap operator that takes inner and outer observable and you combine them together.

    http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-switchMap

    Here is an example:

     Rx.Observable.of(1)
        .switchMap(x=>Rx.Observable.of(x+1), (outer, inner) => ({outer, inner}))
     .subscribe(x=>console.log(x))
    

    It will print

    {
     inner: 2,
     outer: 1
    }