import * as googleMaps from '@google/maps';
constructor() {
this.googleMapClient = googleMaps.createClient({
key: 'whatever'
});
}
//获取项目列表的服务,为每个项目调用addLocation并返回更新项目列表。
public setItems(): Observable< Item[]> {
return new Observable(observer => {
this.getItems()
.flatMap((items: Item[]) => {
console.log('i get to this point correctly', items);
const obs = items.map(item => {
return new Observable(observer2 => {
this.addLocation(item)
.subscribe(data => {
observer2.next(item);
observer2.complete();
});
});
});
return Observable.forkJoin(obs);
})
.subscribe(data => {
observer.next(data);
observer.complete();
});
});
}
//为每个项目获取位置的服务
private addLocation(item): Observable< item> {
return new Observable(observer => {
this.getLocationDescription(item.location.latitude, item.location.longitude)
.subscribe((response: string) => {
item.location.description = response;
observer.next(activity);
observer.complete();
});
});
}
//从谷歌地图获取位置的服务
private getLocationDescription(latitude:number, longitude: number): Observable<any> {
return new Observable(observer => {
const latlng = {
lat: latitude,
lng: longitude
};
this.googleMapClient.reverseGeocode({
latlng: latlng
}, ((status, results) => {
const data = results.json;
if (data.status === 'OK') {
const locationData = data.results[0];
const address = this.extractAddress(locationData);
const locationResults: string[] = [];
let locationName: string;
locationResults.push(this.getFirstDefinedProperty(address,
['neighborhood', 'administrative_area_level_4', 'administrative_area_level_3', 'sublocality', 'route']));
locationResults.push(this.getFirstDefinedProperty(address,
['locality', 'postal_town', 'administrative_area_level_2', 'administrative_area_level_1']));
locationName = locationResults.join(',');
observer.next(locationName);
observer.complete();
} else {
observer.error(status);
}
})
);
});
}
//组件
this.itemService.setItems()
.subscribe(items => {
this.items = items;
// console.log here show the right listt
});
//组件模板
<div *ngFor="let item of items">{{item.location.description}}</div>
所有内容似乎都正确执行,在我的组件中,我获得了具有正确位置的更新项目列表,但html中没有显示任何内容。
我已经测试过返回一个简单的值而不是谷歌地图位置,一切正常,所以看起来这个问题与谷歌地图方法有关。
答案 0 :(得分:0)
我想您忘记在return
之前添加this.getItems()
:
return this.getItems()