作者:mk艾草_180 | 来源:互联网 | 2023-02-03 14:46
我尝试使用Google Places Js API检索Google Places,并使用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= 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();
}
}
并查看:
{{place.name}} - {{place.rating}}
{{place.vicinity}}
有什么办法吗?
1> Günter Zöchb..:
众所周知,谷歌地图使代码在Angulars区域外运行,这种“中断”更改检测。使更新模型的代码明确在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);
});