angularjs和$http请求
angularjs和$http请求
你好,我是AngularJS的新手,正在尝试从我的服务器获取JSON数据。当服务被执行时,我在Fiddler中看到了一个明确的响应。但是成功或错误函数没有被执行,所以服务返回一个空数组。
var app = angular.module('imageApp', []);
app.service('imageService', function ($http) {
var imageModels = [];
this.Images = function (url) {
$http({ method: 'GET', url: url }).then(function (response) {
imageModels = response.data;
}).catch(function (error) {
imageModels = error.data || "请求失败";
});
return imageModels;
};
});
app.controller('ImageController', function (imageService, $scope) {
$scope.fetch = function (url) {
$scope.url = url;
$scope.ImageModels = imageService.Images($scope.url);
};
});
在使用AngularJS的$http服务发送请求时,可能会遇到异步返回结果的问题。由于$http返回结果是异步的,所以在调用return imageModels
时,success()或error()回调函数可能还没有执行。因此,我们需要等待$http创建的promise对象被解析,可以在控制器中使用then()方法来解决这个问题。
具体的解决方法可以参考BD在stackoverflow上给出的解决方案:https://stackoverflow.com/a/12513509/215945