我正在使用Google Maps API来获取两点之间的距离。此方法使用回调函数。问题是这个代码位于Angular服务中,我想从控制器调用它,因此控制器可以在范围内输出结果。但是我不知道服务如何将生成的 hospital [] 对象数组返回给控制器。我怎么能做到这一点?
myAppServices.service('NearestHospitalService', function(){
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
var hospitals = [];
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
}
else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
for (var j = 0; j < results.length; j++) {
hospitals.push(new hospital(destinations[j], results[j].distance, results[j].duration));
}
hospitals.sort(compareDistance);
}
}
});
答案 0 :(得分:4)
我将添加一些伪代码,以帮助您找到正确的方向。基本上使用回调,您需要将回调一直回到您想要使用您的价值的位置。
AngularJS有一个未来/承诺模块,也称为$ q。我不会用它,但你应该看看它。
myAppServices.service('NearestHospitalService', function(){
var api = {};
api.calculateDistances = function(callBack) {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, extractResult);
function extractResult(response, status) {
... do computations on you response ...
callback(transformedResponse);
}
};
return api;
});
然后你这样称呼它:
$scope.distances = [];
NearestHospitalService.calculateDistances(function( ds ) { $scope.distances = ds; });
另一种方法是注入$ rootScope并使用广播,如果您的代码中有多个组件需要知道已更新的内容,以便他们可以提取所需内容。
在这种情况下,您会在服务中缓存响应
myAppServices.service('NearestHospitalService', ['$rootScope', function($rootScope){
var api = {};
api.distances = [];
api.calculateDistances = function() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, extractResult);
function extractResult(response, status) {
... once again calculate ...
api.distances = transformedResult;
$rootScope.$broadcast('updatedDistances'); // you could also send distances as an argument directly if you wanted to.
}
};
return api;
}]);
然后你需要收听广播并获取缓存。
$rootScope.$on('updatedDistances', function(event) { $scope.distances = NearestHospitalService.distances });