9

我正在尝试使用 $http,但为什么它返回空结果?

angular.module('myApp')
.factory('sender', function($http) {
    var newData = null;
    $http.get('test.html')
        .success(function(data) {
            newData = data;
            console.log(newData)
        })
        .error(function() {
            newData = 'error';
        });
    console.log(newData)
    return newData
})

控制台说:http ://screencast.com/t/vBGkl2sThBd4 。为什么我的 newData 首先是 null 然后被定义?如何正确执行?

4

2 回答 2

20

正如 YardenST 所说,$http它是异步的,因此您需要确保依赖于您返回的数据的所有函数或显示逻辑都$http.get()得到相应的处理。实现此目的的一种方法是利用$http返回的“承诺”:

Plunkr 演示

var myApp = angular.module('myApp', []);

myApp.factory('AvengersService', function ($http) {

    var AvengersService = {
        getCast: function () {
            // $http returns a 'promise'
            return $http.get("avengers.json").then(function (response) {
                return response.data;
            });
        }
    };

    return AvengersService;
});


myApp.controller('AvengersCtrl', function($scope, $http, $log, AvengersService) {
    // Assign service to scope if you'd like to be able call it from your view also
    $scope.avengers = AvengersService;

    // Call the async method and then do stuff with what is returned inside the function
    AvengersService.getCast().then(function (asyncCastData) {
            $scope.avengers.cast = asyncCastData;
    });

    // We can also use $watch to keep an eye out for when $scope.avengers.cast gets populated
    $scope.$watch('avengers.cast', function (cast) {
        // When $scope.avengers.cast has data, then run these functions
        if (angular.isDefined(cast)) {          
            $log.info("$scope.avengers.cast has data");
        }
    });
});
于 2013-03-17T11:04:10.007 回答
5

此 JavaScript 代码是异步的。

console.log(newData)
return newData

在什么里面执行之前success

newData = data;
console.log(newData)

所以第一次,newData 为空(你设置为空)

并且当返回 http 响应时(在成功内), newData 将获得它的新值。

这在 Javascript 中很常见,您应该在success.

于 2013-02-03T10:44:32.390 回答