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

Ili*_*lia 9 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
})
Run Code Online (Sandbox Code Playgroud)

控制台说:http://screencast.com/t/vBGkl2sThBd4.为什么我的newData首先为null然后定义?怎么做正确?

GFo*_*y83 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");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)


Yar*_*nST 5

此JavaScript代码是异步的.

console.log(newData)
return newData
Run Code Online (Sandbox Code Playgroud)

在内部执行之前执行 success

newData = data;
console.log(newData)
Run Code Online (Sandbox Code Playgroud)

所以第一次,newData为null(你将它设置为null)

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

这在Javascript中非常常见,你应该在里面完成你所有的工作success.