不能与$ HTTP angularjs得到的结果数据(Can't get result da

2019-08-16 17:49发布

我试图使用$ 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首先是空,然后定义? 如何正确做呢?

Answer 1:

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


Answer 2:

这段JavaScript代码是异步的。

console.log(newData)
return newData

之前有什么内部执行success

newData = data;
console.log(newData)

因此,在第一次,newData为空(你将其设置为null)

当返回HTTP响应(成功内),该newData获取其新的价值。

这是很常见的Javascript,你应该做的里面你所有的工作success



文章来源: Can't get result data with $http angularjs