如何在angularjs工厂中调用函数

How to call function in angularjs factory

本文关键字:调用 函数 工厂 angularjs      更新时间:2023-09-26

这是我的工厂,我想在saveData中调用getData。这是我的代码

.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: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();
      }
  }
})

您不必在返回的对象字面量中声明所有函数。你可以这样做:

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的样式指南