Can't get result data with $http angularjs

前端 未结 2 1598
北海茫月
北海茫月 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: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");
            }
        });
    });
    

提交回复
热议问题