2016-11-05 6 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에 어떻게 사용할 수 있습니까? 당신의 saveData 방법 내부

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

을이 당신을 위해 무엇을 찾고있는 무언가 경우 알려주세요 -

답변

2

당신은 항상 이런 식으로 뭔가를 할 수 있습니다.

작업 예 - 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을보십시오.

관련 문제