簡體   English   中英

如何在angularjs工廠中調用函數

[英]How to call function in angularjs factory

這是我的工廠,我想在 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 的樣式指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM