我试图做一些地理定位并基于坐标,调用返回一些数据的RESTful API。然后我想解析这些数据,最后返回它 我对angular.js和promises很新,因此这段代码是我通过互联网看到的一些东西:D以角度返回链接承诺的“最后”值
我已经使所有工作,但我错过了最后一步:返回处理结果数组(“allSpots”)到原来的调用者。我在这里错过了什么?
.factory('wifiSpotFactory', function (WifinderModel, $q, $http) {
function onGeolocationSuccess(position) {
var url = 'http://localhost:34915/api/spots?latitude=' + position.coords.longitude + '&longitude=' + position.coords.latitude;
$http.get(url).then(function (response) {
var allSpots = [], data = response.data;
for (var i = 0; i < data.length; i++) {
var newSpot = new WifinderModel.wifiSpot(data[i].id, data[i].name, data[i].password, data[i].address);
allSpots.push(newSpot);
}
return allSpots;
}, function (error) {
console.log(error);
});
};
var wifiSpotFactory = {
loadNearSpots: function() {
var geo_options = {
enableHighAccuracy: true,
maximumAge: 50000,
timeout: 30000
};
var deferred = $q.defer();
navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject, geo_options);
return deferred.promise
.then(onGeolocationSuccess)
.then(function(allSpots) { return allSpots; });
}
};
return wifiSpotFactory;
})
然后在控制器中,我该如何检索promise的值?
.controller('wifiListController', [
'$scope', 'wifiSpotFactory', function ($scope, wifiSpotFactory) {
$scope.spots = wifiSpotFactory.loadNearSpots();
}
])
那么,是什么'WifinderModel.wifiSpot()'返回 - 值或承诺? –
返回一个值 - 类 –
毫米的实例,在这种情况下,Pankaj Parkar的解决方案看起来应该起作用。 –