AngularJS:如何将我从工厂返回值,如果数据获取与HTTP(AngularJS : How w

2019-10-19 05:03发布

我有这个厂的角度:

'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方法)没有更新成功。 我如何去使这项工作?

Answer 1:

还有你可以改变一些东西。 (和方式,你可以改变它们)。 1是最推荐/正确。

  1. 使用的承诺,回调在控制器等等...

     // 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 = []; 而不是仅仅消灭它。 例如。 遍历W /为幂等在角度需要结合Ë对象的新数据和压入/弹出不印字,CONCAT

要记住的另一件事是,服务实例化一次。 当正在创建和销毁所有的时间控制器..你可能不必每次都作出请求,以便也许在返回$ HTTP承诺之前getTransactions你可以检查,看看是否需要作出请求。 然后手动使用的承诺。



文章来源: AngularJS : How would i return value from factory if the data is fetched with http