0
votes

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.

2
what would be the condition? - Jota.Toledo
The home world value is conditioned on the fetched character value - amit

2 Answers

2
votes

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
}
1
votes

Inside of the mergeMap operator you could manipulate the outer observable (source) and combine it with the inner one by means of a resultSelector:

const example = Rx.Observable.of('Hello')
  .mergeMap(v => Rx.Observable.of(v +" Rxjs"),(valueFromSource,valueFromInner)=>{
      return `Source: ${valueFromSource}, Inner: ${valueFromInner}`;
});
//output: "Source: Hello, Inner: Hello Rxjs"
const subscribe = example.subscribe(val => console.log(val));

You can check a live example here

More information about mergeMap can be found here