且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

angularjs和$ http请求

更新时间:2022-10-29 13:36:18

$ HTTP返回结果异步。因此,收益imageModels 将成功()或错误之前执行()回调有机会运行。你需要等待$ HTTP创建解决的承诺 - 使用则()在你的控制器

而不是这里就不重复了,看到@Pete BD解决方案: http://***.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://***.com/a/12513509/215945