无法使用$ http angularjs获取结果数据

时间:2013-02-03 10:38:28

标签: http angularjs

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

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然后定义?如何正确地做到这一点?

2 个答案:

答案 0 :(得分:20)

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

Plunkr Demo

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");
        }
    });
});

答案 1 :(得分:5)

此JavaScript代码是异步的。

console.log(newData)
return newData

success

内部执行
newData = data;
console.log(newData)

因此,第一次,newData为null(您将其设置为null)

当返回http响应时(在成功内部),newData获取其新值。

这在Javascript中非常常见,您应该在success内完成所有工作。