AngularJS:如果使用http获取数据,我将如何从工厂返回值

时间:2014-01-15 01:42:40

标签: angularjs angularjs-factory

我有角度的这家工厂:

'use strict';

angular.module('finansiiApp')
  .factory('transactions', function ($http) {
    var transactions = [];
    $http.get("/api/transactions.json")
      .success(function(data, status){
        transactions = data;
      });

    // Public API here
    return {
      getTransactions: function () {
        return transactions;
      },
      addTransaction: function(transaction){
        transactions.push(transaction);
      }
    };
  });

这是我的控制者:

'use strict';

angular.module('finansiiApp')
  .controller('MainCtrl', function ($scope, transactions) {
    $scope.searchText = "";
    $scope.filterPrimanja = $scope.filterTrosoci = true;
    console.log(transactions);
    $scope.transactions = transactions.getTransactions();
    $scope.clicked = function(index){
      console.log(index);
    }
  });

现在您可能已经猜到,我在控制器中的数据(我称之为getTransactions方法)未成功更新。我将如何开展这项工作?

1 个答案:

答案 0 :(得分:2)

您可以更改一些内容。 (以及你可以改变它们的方法)。 1是最建议/正确的。

  1. 在控制器中使用promises和callback,以便......

    // your controller... ($scope.transactions line)
    transactions.getTransactions().then(function(data){
        $scope.transactions = data;
    }
    
    // your service..
    angular...factory('transactions',function($http,$q){
        var transactions = [];
        return {
            getTransactions: function(){
               //is a request needed?
               if(transactions.length > 0){
                   var deferred = $q.defer();
                   deferred.resolve(transactions);
                   return deferred.promise;
               }
               return $http.get("/api/transactions.json").then(function(result){
                   //modify collection of transactions...
                   transactions = result.data;
                   return transactions; // this is data ^^ in the controller
               });
            }
            addTransaction: function(transaction){
                //do more http stuff?
                //wrap function in promise so its consistent and will also run digest.
                var deferred = $q.defer();
                transactions.push(transaction);
                deferred.resolve(transactions);
                return deferred.promise;
            }
        }
    
    });
    
  2. 修改var transactions = [];而不是仅删除它。例如。迭代新数据并推送/弹出unshift,concat w / e绑定角度的对象需要是幂等的

  3. 要记住的另一件事是服务只被实例化一次。虽然控制器一直在被创建和销毁。您可能不必每次都发出请求,所以也许在getTransactions中返回$ http promise之前,您可以检查是否需要发出请求。然后手动使用承诺。