gpt4 book ai didi

AngularJS 1.2.0 $resource 响应为空

转载 作者:行者123 更新时间:2023-12-02 18:59:34 24 4
gpt4 key购买 nike

我正在使用 AngularJS 1.2.0。当我使用 $resouce 调用 Web 服务时,响应变量始终为空。 Web 服务被正确调用,并且 Web 服务正在将结果发送到浏览器。问题是 (callback(response){}) 响应始终为空。

angular.module('app').factory('geoCoding',['$resource', function ($resource) {
return $resource('http://open.mapquestapi.com/geocoding/v1/address', {key: getGeoKey()}, {
locate: {method: 'GET', isArray: false}
});
}]);

$scope.getLocations = function (locationName) {
return geoCoding.locate({location: locationName}).$promise.then(
function (response) {
log.log('response ', response);
if (response && response.data && response.data.results && response.data.results[0]) {

var locations = [];

response.data.results[0].locations.forEach(function (location) {
locations.push({name: geoUtils.location2String(location), location: location});
});

return locations;
} else {
return {};
}

}, function (error) {
log.error('Locations Query error: ', error);
});
};

最佳答案

以下是使用 1.2.0rc1 的几种不同方法。

var app = angular.module('app', ['ngResource']);
app.factory('geoCoding',['$resource', function ($resource) {
return $resource('response.json', {key: 123}, {
locate: {method: 'GET', isArray: false}
});
}]);

app.controller('MainCtrl', function($scope,geoCoding){
// bind it directly to the async result
$scope.locations = geoCoding.locate({location: "a location"});

// use a function to trigger the request
$scope.getLocations = function () {
$scope.resp = geoCoding.locate({location: "a location"});
};

// use a function to trigger the request using the promise
$scope.getLocationsAlt = function() {
geoCoding.locate({location: "a location"}).$promise.then(function(response){
$scope.respAlt = response;
}, angular.noop);
};
});

根据评论更新

您面临的问题似乎是数据以意外的格式返回。更新后的代码如下所示 ( http://plnkr.co/edit/xzZHvm?p=preview ):

var app = angular.module('app', ['ngResource']);
app.factory('geoCoding',['$resource', '$http', '$log', function ($resource, $http, $log) {
return $resource('http://open.mapquestapi.com/geocoding/v1/address', {}, {
locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter) {
// probably be better if you examined the results in here
$log.info(data.results[0]);
return data.results[0].locations;
})}
});
}]);
app.controller('MainCtrl', function($scope, $log, geoCoding){
$scope.locations = geoCoding.locate({location: "Dallas, TX"});
});

关于AngularJS 1.2.0 $resource 响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com