您好,我是 AngularJs 的新手,正在尝试从我的服务器获取 json 数据。当服务执行时,我在 Fiddler 中看到了清晰的响应。但是 success 或 error 函数没有被执行,因此服务返回一个空数组。
var app = angular.module('imageApp', []);
app.service('imageService', function ($http) {
var imageModels = [];
this.Images = function (url) {
$http({ method: 'GET', url: url }).success(function (data) {
imageModels = data;
}).error(function (data) {
imageModels = data || "Request failed";
});
return imageModels;
};
};
});
app.controller('ImageController', function (imageService, $scope) {
$scope.fetch = function (url) {
$scope.url = url;
$scope.ImageModels = imageService.Images($scope.url);
};
});
最佳答案
$http 异步返回结果。因此,return imageModels
将在 success() 或 error() 回调有机会运行之前执行。您需要等待 $http 创建的 promise 来解决——在 Controller 中使用 then()。
与其在这里重复,请参阅@Pete BD 的解决方案:https://stackoverflow.com/a/12513509/215945
关于javascript - angularjs 和 $http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14773857/