角度返回来自Google PlacesService并添加到Observable

时间:2018-03-06 15:26:47

标签: angular firebase observable google-places-api

使用下面的方法,我可以使用placeId成功检索地点详细信息。

getPlaceDetails(placeId) {
    this.mapsAPILoader.load().then(() => {
      const service = new google.maps.places.PlacesService($('#service-helper').get(0));
      service.getDetails({'placeId': placeId}, (results, status) => {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          if (results) {
            console.log(results);
          }
        }
      });
    });
  }

我有另一种方法用于从Firebase(Firestore)检索我的所有客户,我试图通过传递每个placeId来添加我从getPlaceDetails收到的详细信息,但我不知道如何从中获取结果getPlaceDetails并在映射时将它们添加到每个安装程序。我的目标是让getInstallers()返回类似return {id,... data,... results}的内容。非常感谢任何帮助!

getInstallers(): Observable<Installer[]> {
    const installersCollection = this.afs.collection<Installer>('installers');
    return installersCollection.snapshotChanges().map(installers => {
      return installers.map(i => {
        const data = i.payload.doc.data() as Installer;
        const id = i.payload.doc.id;
        this.getPlaceDetails(data.placeId);
        return { id, ...data };
      });
    });
  }

这是stackblitz上的一个非常简化的版本:https://stackblitz.com/edit/angular-23mu7g

1 个答案:

答案 0 :(得分:3)

嘿,这是一个有效的解决方案:

live example

请注意,当您需要使用角度方式直接与DOM交互时,不会推荐此行(它使用Jquery):

const service = new google.maps.places.PlacesService($('#service-helper').get(0));

Angular方式:

@ViewChild('serviceHelper') serviceHelper;

由于您要更改paginator和sort指令的值,您可能会收到此错误:ExpressionChangedAfterItHasBeenCheckedError您应该触发detecChanges()方法,但首先导入changeDetectorRef

import { ..., ChangeDetectorRef } from '@angular/core';
this.ref.detectChanges();

请记住,当您直接引用DOM中的元素(使用@ViewChild装饰器)时,在执行ngAfterViewInit之前它们不可靠。的 app.component.ts

    import {Component, ViewChild, ChangeDetectorRef } from '@angular/core';
    ...
    @ViewChild('serviceHelper') serviceHelper;
    ...

    constructor(private mapsAPILoader: MapsAPILoader, private ref: ChangeDetectorRef) {}
    ngAfterViewInit() {
    // Create 100 users
    const businesses = [
        {placeId: 'ChIJHWJmnEbxxokRxI5WpqIW9jo'},
        {placeId: 'ChIJeUdT2ikPK4cRpqJK61nKvuk'},
        {placeId: 'ChIJ24q4qLMsDogRkwzJD2maZcw'},
    ];

    const updatedBusinesses = []

    businesses.forEach(business => {
        this.getPlaceDetails(business.placeId)
            .subscribe(place => {
                console.log(place);
                updatedBusinesses.push({
                    placeId: business.placeId,
                    name: place.name,
                    rating: place.rating
                });
                // Assign the data to the data source for the table to render
                this.dataSource = new MatTableDataSource(updatedBusinesses);
                this.dataSource.paginator = this.paginator;
                this.dataSource.sort = this.sort;
                this.ref.detectChanges();
            });
    })
  }
...
getPlaceDetails(placeId): Observable<any> {
    const callback = (results, status) => {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          if (results) {
            return results;
          }
        }
      };

    return this.loadMapsApi().pipe(concatMap(place => {
        const service = new google.maps.places.PlacesService(this.serviceHelper.nativeElement);
        let $getDetailsAsObservable : any;

        $getDetailsAsObservable = bindCallback(service.getDetails.bind(service), callback);
        return $getDetailsAsObservable({'placeId': placeId}); 
    }));
  }

  loadMapsApi(): Observable<any> {
      const $mapsAPILoader = fromPromise(this.mapsAPILoader.load());
      return $mapsAPILoader;
  }

<强> app.component.html

...
    <div id="service-helper" #serviceHelper></div>
...