我尝试使用Google Places Js API检索Google商家信息并使用BehaviorSubject.next通过异步管道更新我的Angular视图,但视图未更新。
实际上有时它会在15秒后完成。有时我必须点击某个地方。但我确定的是,当我从Google服务器获得结果时它不会更新...(我控制台登录)。
这是我的搜索功能:
import { AfterViewInit, Component, ViewChild, ElementRef } from '@angular/core';
import { LoadingController, NavParams, ViewController, Platform } from 'ionic-angular';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
declare var google;
@Component({
selector: 'page-new-location-modal',
templateUrl: 'new-location-modal.html'
})
export class NewLocationModalPage {
@ViewChild('map') map: ElementRef;
// ngModel for segment
googleSearchType: string;
// Sport retrieved from previous page (newEventForm)
sport = '';
// Props used for suggestion func
mapElem: ElementRef;
googleService: any;
places$:BehaviorSubject<any[]>= new BehaviorSubject([]);
constructor(
public platform: Platform,
public viewCtrl: ViewController,
public loadingCtrl: LoadingController,
public params: NavParams
) {
console.log('NewLocationModal#constructor');
// Sport must be retrieved from params
this.sport = params.get('sport');
}
ngAfterViewInit(): void {
// Init Google service
this.mapElem = this.map.nativeElement;
this.googleService = new google.maps.places.PlacesService(this.mapElem);
// Select Suggestion segment
this.googleSearchType = 'suggestion';
// Trigger searchSuggestionsForSport()
this.searchSuggestionsForSport(this.sport);
}
onSegmentChange(segment): void {
console.log('NewLocationModal#onSegmentChange - Selected segment ', segment.value);
if (segment.value === 'suggestion') {
this.searchSuggestionsForSport(this.sport);
}
}
searchSuggestionsForSport(sport: string): void {
console.log('NewLocationModal#searchSuggestionsForSport - Sport ', sport);
let location = new google.maps.LatLng(48.862725,2.287592000000018);
let request = {
location: location,
keyword: sport,
rankBy: google.maps.places.RankBy.DISTANCE
};
// Google Places Service
// NearBy Search
this.googleService.nearbySearch(request, (places) => {
// First set of information sent to the async pipe in view
this.places$.next(places);
console.log(places);
});
}
dismiss() {
this.viewCtrl.dismiss();
}
}
并查看:
<div *ngFor="let place of places$ | async">
<ion-card>
<ion-card-content>
<ion-card-title>
{{place.name}} - {{place.rating}}
</ion-card-title>
<p>
{{place.vicinity}}
</p>
</ion-card-content>
</ion-card>
</div>
任何解决方案?
答案 0 :(得分:4)
众所周知,Google地图可以让代码在Angulars区域之外运行,而且#34;中断#34;改变检测。使更新模型的代码明确地在Angulars区域内运行:
constructor(
public platform: Platform,
public viewCtrl: ViewController,
public loadingCtrl: LoadingController,
public params: NavParams,
private zone:NgZone,
) {
...
// NearBy Search
this.googleService.nearbySearch(request, (places) => {
// First set of information sent to the async pipe in view
this.zone.run(() => this.places$.next(places));
console.log(places);
});