Processing $http response in service

后端 未结 12 1673
半阙折子戏
半阙折子戏 2020-11-22 03:36

I recently posted a detailed description of the issue I am facing here at SO. As I couldn\'t send an actual $http request, I used timeout to simulate asynchrono

12条回答
  •  礼貌的吻别
    2020-11-22 04:20

    A much better way I think would be something like this:

    Service:

    app.service('FruitsManager',function($q){
    
        function getAllFruits(){
            var deferred = $q.defer();
    
            ...
    
            // somewhere here use: deferred.resolve(awesomeFruits);
    
            ...
    
            return deferred.promise;
        }
    
        return{
            getAllFruits:getAllFruits
        }
    
    });
    

    And in the controller you can simply use:

    $scope.fruits = FruitsManager.getAllFruits();
    

    Angular will automatically put the resolved awesomeFruits into the $scope.fruits.

提交回复
热议问题