angularjs和$ http请求angularjs、http

2023-09-13 03:45:00 作者:霸道、是我的个性

您好我是新来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

混合式框架AngularJS

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