0

In following code snippet. First I am getting lat lng from GeoCode service that returns Observable.After that I am making http call that again returns an observable

 getData(next?) {

       return this.geoCode.getCurrentLocation().map(latlng => {
           console.log(latlng);
            var url = this.API_URL + "?location=" + latlng + "&radius=" + this.radius;
            if (next != undefined) {
                url = this.API_URL + "?location=" + latlng + "&radius=" + this.radius + "&next=" + next;
            }
            return this._http.get(url).map(res=>res.json());

        });

};

above method is returning Observable<Observable<any>> but I want to return Observable<any>

  • 2
    Use the switchMap operator. http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-switchMap – JB Nizet Apr 13 '17 at 14:47

1 Answers1

6

You have to use flatMap in place of map :

 getData(next?) {           
       return this.geoCode.getCurrentLocation().flatMap(latlng => { //HERE !
           console.log(latlng);
            let url = this.API_URL + "?location=" + latlng + "&radius=" + this.radius;
            if (next != undefined) {
                url = this.API_URL + "?location=" + latlng + "&radius=" + this.radius + "&next=" + next;
            }
            return this._http.get(url).flatMap(res=>res.json()); //AND HERE !

        });

};

A great reading here : Why we need to use flatMap?

Community
  • 1
  • 1
Karbos 538
  • 2,977
  • 1
  • 23
  • 34