user3698593
user3698593

Reputation:

Return observable from observable in angular 2

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>

Upvotes: 0

Views: 8646

Answers (1)

Karbos 538
Karbos 538

Reputation: 3055

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?

Upvotes: 6

Related Questions