angularrxjsobservablegoogle-places

Angular2 Observable - how to wrap a third party ajax call


I'm using Google's places api - getPlacePredictions.

Here is my code on my input keyup event:

My template:

<input type="text" (keyup)='search()'>
<div *ngIf="searching">Searching ... </div>

My Class:

private autocomplete;

ngAfterViewInit () {
    this.autocomplete = new google.maps.places.AutocompleteService();
}

search(){
    this.searching = true;
    this
    .autocomplete
    .getPlacePredictions( option , ( places , m )=> {
        console.log( 'onPrediction' , places ); 
        this.searching = false;
    } ); 
}

Is there any practicable way to wrap getPlacePredictions, inside a rxjs observable so I can take advantage of subscribing to this function ?

What I'm trying to do eventually here is to create a loading icon visible and invisible, but I can't make it properly with the google's api itself, I guess if I could wrap it inside an Observable, it would become easy.


Solution

  • You could wrap the call to the getPlacePredictions method within a raw observable this way:

    search(option) {
      return Observable.create((observer) => {
        this.autocomplete
          .getPlacePredictions( option , ( places , m )=> {
            observer.next(places);
          }); 
      });
    }
    

    Then you will be able to subscribe to it:

    this.searching = true;
    this.search(option).subscribe(places => {
      this.searching = false;
      this.places = places;
    });
    

    As of later Angular versions https://stackoverflow.com/a/55539146/13889515

    Use:

    return new Observable((observer) => {
      this.autocomplete
        .getPlacePredictions( option , ( places , m )=> {
           observer.next(places);
         }); 
      });
    }