angularjs $http.get to get json not working in the service layer

后端 未结 2 980
既然无缘
既然无缘 2020-12-31 10:19

I am developing an angularjs app as a part of my angularjs learning. I have controllers and from there I am calling service layers.

leagueManager.service(&quo         


        
相关标签:
2条回答
  • 2020-12-31 10:26

    Yeah you will need to use a promise interface. So instead of returning a teams object, directly you'll have to return a promise:

    Promise Resources:

    • http://egghead.io/lessons/angularjs-promises
    • http://docs.angularjs.org/api/ng.$q

    In the service:

    leagueManager.service("teamsService", function($http){
        var deferred = $q.defer();
        $http.get('data/teams.json').then(function(data) {
            deferred.resolve(data);
        });
        this.getTeams = function(){
            return deferred.promise;
        };
    });
    

    Then in the controller:

    $scope.team = {};
    
    var promise = teamsService.getTeams();
    promise.then(function(data) {
        $scope.teams = data;
    });
    
    0 讨论(0)
  • 2020-12-31 10:45

    This should work fine:

    myApp.factory('mainFactory',['$http',function($http){
    
    var mainFactory = {};
    
    mainFactory.getRandomUser = function(){
        var promise;
        if(!promise){
            promise = $http.get('http://api.randomuser.me/').success(function(d){
                return d;   
            });
            return promise;
        }
    };
    
    mainFactory.getRandomImage = function(){
        var promise;
        if(!promise){
            promise = $http.get('http://lorempixel.com/400/200/').success(function(d){
                return d;   
            });
            return promise;
        }
    };
    
    return mainFactory;
    
    }]);
    
    0 讨论(0)
提交回复
热议问题