2016-11-05 13 views
0

これは私の工場であると私はsaveData.HereでのgetDataを呼び出したいのは私のコード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から返された約束をsaveDataにどのように使用できますか?

答えて

2

あなたはいつも、このような何か行うことができます - これはあなたが探しているものに何かあるなら、私に知らせて、あなたのsaveDataメソッド内

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

を。

実施例 - 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をご覧ください。

関連する問題