javascriptangularjsangular-promise

How to call function in angularjs factory


this is my factory and i want to call getData in saveData.Here is my code

.factory('dataSyncOperation', function($q,$http){
return {
    getData:function(){
        var q = $q.defer();
         var config = {
                    headers : {
                        'Content-Type': 'application/json'
                    }
                }
         $http.get(api+'/sync/').then(function(response){
            q.resolve(response);
        },function(error){
            q.reject();
        })
        return q.promise;

    },

    saveData:function(){

    }

}

}); How can i use the promise returned by getData into saveData.


Solution

  • You can always do, something like this -

    saveData:function(){
      this.getData().then(function(response){ // you can handle getData promise here
         // on success 
      }, function(reject){
         // on failure
      });
    }
    

    inside your saveData method, let me know if this is what something you are looking for.

    Working Example - http://plnkr.co/edit/y8WZQT8SvOAWpKj8Jgxs?p=preview

    Code -

    // Code goes here
    
    var myApp = angular.module('myApp', []);
    
    myApp.controller('mainCtrl', function($scope, testService){
      testService.saveData().then(function(res){
        $scope.test = res.data;  
      });
    })
    
    myApp.factory('testService', function($q, $http){
      return {
          getData:function(){
            var q = $q.defer();
            $http.get('data.json').then(function(response){
              q.resolve(response);
            }, function(error){
                q.reject();
            })
            return q.promise;
          },
          saveData:function(){
            return this.getData();
          }
      }
    })