2016-11-05 83 views
0

這是我的工廠,我想呼籲的getData在saveData.Here是我的代碼如何調用函數angularjs工廠

.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(){ 

    } 

} 

}); 如何將getData返回的promise使用saveData。

回答

2

你總是可以做的,是這樣的 -

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

saveData方法裏面,讓我知道,如果這是你在找什麼東西。

工作實例 - http://plnkr.co/edit/y8WZQT8SvOAWpKj8Jgxs?p=preview

碼 -

// 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(); 
     } 
    } 
}) 
1

我不必申報對象字面返回的所有功能。你可以這樣做:

factory('dataSyncOperation', function($q,$http){ 

    function getData(){ //you can declare function inside function and it will be avaible only inside scope of outer 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; 

    } 

    getData(); //call get data 

    function saveData() { 
      myPrivateFunction(); 
      getData(); //call get data inside save data 
    } 

    function myPrivateFunction(){ //you can even have private functions not avaible from outside 

    } 

    return { //declare which functions will be available from outside 
     getData:getData, 
     saveData:saveData 

     } 
}); 

這種方式甚至被優先考慮。請看angular's style guide