angularjs和$ http请求 [英] angularjs and $http request
问题描述
您好我是新来AngularJs并试图从我的服务器获取JSON数据。当服务被执行,我看到提琴手明确回应。但是,成功或错误的功能没有得到执行,所以服务返回一个空数组。
VAR应用= angular.module('ImageApp程序',[]);app.service('imageService',函数($ HTTP){
变种imageModels = [];
this.Images =功能(URL){
$ HTTP({方法:GET,URL:})。成功(功能(数据){
imageModels =数据;
})错误(功能(数据){
imageModels = ||数据请求失败;
}); 返回imageModels;
};
};
});app.controller('ImageController',函数(imageService,$范围){
$ scope.fetch =功能(URL){ $ scope.url =网址;
$ scope.ImageModels = imageService.Images($ scope.url);
};
});
$ HTTP返回结果异步。因此,收益imageModels
将成功()或错误之前执行()回调有机会运行。你需要等待$ HTTP创建解决的承诺 - 使用则()在你的控制器
而不是这里就不重复了,看到@Pete BD解决方案: http://stackoverflow.com/a/12513509/215945
Hello I'm new to AngularJs and trying to get json Data from my server. When the service gets executed, I see a clear response in Fiddler. But the success or the error function does not get executed, and so the service returns an empty array.
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 returns results asynchronously. So, return imageModels
will execute before the success() or error() callbacks have had a chance to run. You need to wait for the promise that $http creates to resolve -- use then() in your controller.
Rather than repeat it here, see the solution from @Pete BD: http://stackoverflow.com/a/12513509/215945
这篇关于angularjs和$ http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!