我正在尝试使用Google地图API在某个位置使用此库查找医院:https://developers.google.com/maps/documentation/javascript/places。
我成功地在控制台中发出请求并显示结果但是我想将结果放在变量中以使用html页面中的ngFor显示它,这就是我发现此问题的地方。enter image description here
这是我的代码:
hospSearch_res:any[] = [];
searchHospitals(){
console.log('Search works');
console.log(this.hosp_lat);
console.log(this.hosp_lng);
console.log(this.hosp_rad);
var search_loc = new google.maps.LatLng(this.lat,this.lng);
var request = {
location: search_loc,
radius: '1000',
types: ['hospital']
};
var service = new google.maps.places.PlacesService(document.getElementById('test'));
service.nearbySearch(request, this.callback);
}
callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// this.hospSearch_res = results;
//let res = JSON.stringify(results);
console.log(results);
this.hospSearch_res = results;
for (var i = 0; i < results.length; i++) {
var place = results[i];
//this.hospSearch_res.push(place);
/*console.log(results[i]);
console.log(results[i].name);*/
}
}
}
这是我的第一个角度为2的项目,我对这个问题感到不安,任何帮助都会非常感激。 谢谢
答案 0 :(得分:1)
只需用箭头函数替换回调函数即可绑定this
:
var service = new
google.maps.places.PlacesService(document.getElementById('test'));
service.nearbySearch(request, this.callback);
}
callback = (results, status) => { //Arrow Function Here !
if (status == google.maps.places.PlacesServiceStatus.OK) {
...
}
}