Can't get result data with $http angularjs

前端 未结 2 1581
北海茫月
北海茫月 2021-02-08 21:12

I\'m trying to use $http, but why it return null result?

angular.module(\'myApp\')
.factory(\'sender\', function($http) {
    var newData = null;
    $http.get(\         


        
相关标签:
2条回答
  • 2021-02-08 21:32

    This JavaScript code is asynchronous.

    console.log(newData)
    return newData
    

    Is executed before what inside success

    newData = data;
    console.log(newData)
    

    So at first time, the newData is null (you set it to be null)

    And when the http response is returned (inside the success), the newData gets its new value.

    This is very common in Javascript, you should do all your work inside the success.

    0 讨论(0)
  • 2021-02-08 21:41

    As YardenST said, $http is asynchronous so you need to make sure that all functions or display logic that are dependent on the data that is returned by your $http.get(), gets handle accordingly. One way to accomplish this is to make use of the "promise" that $http returns:

    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");
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题