我有一个Angular.js服务,可以从Google Places API中检索大量的地方搜索结果。然后,该服务继续为每个结果调用详细的位置请求。我试图将生成的JSON传递回控制器。
我认为由于API调用的异步性质,详细结果并非都返回。当我从ResultsActivity记录返回的位置时,我可以看到并非所有结果都存在。但是,我可以在控制台上看到在解析完承诺后返回结果。我试图实现多个promises和$ q.all(),但无济于事。
如果有人能指出我如何使用$q.all
或建议更好的解决方法,我将不胜感激。
谢谢。
PlaceService:
// public/js/services/PlaceService.js
angular.module('Services').factory('PlaceService', ['$http', '$rootScope', '$location', '$q', function($http, $rootScope, $location, $q){
var map;
var service;
var infowindow;
var basicPlaces = [];
var places = [];
function getPlaces(lat, lng, radius){
var deferred = $q.defer();
var promises = [];
function initialize(lat, lng, radius) {
console.log('initialize');
var pyrmont = new google.maps.LatLng(lat,lng);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 12
});
infowindow = new google.maps.InfoWindow();
var request = {
location: pyrmont,
radius: radius,
types: ['store']
};
service = new google.maps.places.PlacesService($("#results")[0]);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
console.log(results[i]);
$("#results").append('<p>'+results[i].name + '\n\n</p>');
createMarker(results[i]);
basicPlaces.push(place);
var defer = $q.defer();
promises.push(defer);
service.getDetails({
placeId: results[i].place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(place);
places.push(place);
console.log(places);
console.log(i);
if (i == results.length) {
console.log("deferring");
defer.resolve(place);
}
}
});
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
initialize(lat, lng, radius);
return $q.all(promises);
}
return {
getPlaces
}
}]);
从ResultsActivity调用服务:
PlaceService.getPlaces($scope.latitude, $scope.longitude, $scope.radius).then(function(places){
$scope.places = places; //Some detailed places are missing here
});