使用可观察的数据订阅返回

时间:2018-06-18 07:21:24

标签: javascript angular typescript ionic-framework ionic3

在下面的代码上几天就一直在努力。

订阅在访问结果后执行。(检查注释)

如何等待订阅完成,以便可以读取并返回结果变量请帮助

place.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { String } from 'typescript-string-operations';
import {Observable} from 'rxjs' 
import  { Response } from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class PlacesProvider {
  apiKey='AIzaSyBuMEEL-0XZX1jSi5yO1GJcuDECegwSD6o';
  baseUrl='https://maps.googleapis.com/maps/api/{0}/json?{1}&key='+this.apiKey;

  constructor(public http: HttpClient) {
  }

nearBy(lat:any,long:any,radius:any):any
{
  var nearbySearchParameters='location='+lat+','+long+'&radius='+radius+'&type=school';
  var apiType='place/nearbysearch';
  var apiUrl=String.Format( this.baseUrl,apiType,nearbySearchParameters);
  console.log("request=>"+apiUrl);
  this.http.get(apiUrl)
  .map(resp=>resp);

}

nearByAddress(address:string,radius:any):any
{
  let nearbysearchResults:Observable<any>;
  let result:any;
  this.getGeoCode(address)
  .subscribe(nbp=>{
             console.log(nbp);//results are here
             result=nbp.results[0];   
          });
          console.log(result); // result is undefined 
          return this.nearBy(result.geometry.location.lat,result.geometry.location.lng,radius); // i want to use this return as observable with pipe on UI which is saying undefined
}

 getGeoCode(address:string):any
{
 var geoCodingPagerameters='address='+address;
  var apiType='geocode';
  var apiUrl=String.Format( this.baseUrl,apiType,geoCodingPagerameters);
  console.log("request=>"+apiUrl);
  var results:any;
  return this.http.get(apiUrl,{ responseType: 'json' })
         .map(resp=>resp);
}

}

Home.ts

getNearbyLcs(): any {
    this.nearbyLcs= this.placesProvider.nearByAddress(this.address.place,'500');
  }

home.html的

<ion-title *ngFor="let lc of (nearbyLcs|async) ">{{lc.name}}</ion-title>

2 个答案:

答案 0 :(得分:0)

好的,这是另一种方法,使用flatMap()。请试一试。

private nearBy(lat: any, long: any, radius: any): Observable<any> {
    const nearbySearchParameters = 'location=' + lat + ',' + long + '&radius=' + radius + '&type=school';
    const apiType = 'place/nearbysearch';
    const apiUrl = String.Format(this.baseUrl, apiType, nearbySearchParameters);

    console.log("request=>" + apiUrl);

    return this.http.get(apiUrl).map(resp => resp);
}

public nearByAddress(address: string, radius: any): Observable<any> {
    let result: any;

    return this.getGeoCode(address)
        .map(nbp => {
            console.log(nbp);//results are here
            result = nbp.results[0];
        }).flatMap(res => {
            return this.nearBy(result.geometry.location.lat, result.geometry.location.lng, radius);
        }).subscribe(data => console.log(data));

}

答案 1 :(得分:0)

只有在需要结果时才能使用switchMap和订阅

private nearBy(lat: any, long: any, radius: any): Observable<any> {
            const nearbySearchParameters = 'location=' + lat + ',' + long + '&radius=' + radius + '&type=school';
            const apiType = 'place/nearbysearch';
            const apiUrl = String.Format(this.baseUrl, apiType, nearbySearchParameters);

            console.log("request=>" + apiUrl);

            return this.http.get(apiUrl).map(resp => resp);
        }

    public nearByAddress(address: string, radius: any): Observable<any> {
        return this.getGeoCode(address)
                   .switchMap(nbp => {
                      let result = nbp.results[0];
                      return this.nearBy(result.geometry.location.lat, 
                               result.geometry.location.lng, radius);
            });
    }

    getNearbyLcs(): any {
                this.placesProvider.nearByAddress(this.address.place,'500')
                    .do(console.log)
                    .subscribe((res) => this.nearbyLcs = res);

      }