2014-09-20 45 views
0

我有一个工厂,我有一个函数getExpenseList,它执行一个查询费用表的ajax调用并给出结果。Angular factory ajax call on every route change

现在我有两条路线,第一条是通过上述功能推动费用的费用列表,第二条路线是增加。当我进行路由更改并返回到列表页面时,再次进行ajax调用。理想情况下,我应该能够将费用对象存储在第一个Ajax调用中,然后引用同一对象,直到有人手动刷新浏览器。

请帮助我。这是我的工厂代码。理想情况下,如果数据存在,我想引用this.expenses。

admin.factory('expenseFact', ['$http', function($http) { 
    var expense = {}; 

    this.expenses = ""; 

    expense.getExpenseList = function() { 
     this.expenses = $http({ 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded' 
      }, 
      method: "GET", 
      url: base_url + "rest/expenses" 
     }); 

     return this.expenses; 
    }; 

    return expense; 
}]); 

这里是我的控制器代码

admin.controller('expenseLandCtrl', function ($scope,$rootScope,expenseFact) { 
    $scope.pageTitle = $rootScope.pageTitle; 

    expenseFact.getExpenseList().then(function (data) { 
     $scope.expenses = data.data; 
    }); 

}); 

admin.controller('expenseAddCtrl', function ($scope,$rootScope,expenseFact) { 
    $scope.pageTitle = $rootScope.pageTitle; 
}); 
+0

我建议你使用模块模式,并在需要时只调用getExpenseList。在你的工厂总是返回费用,这就是为什么它总是会被调用,因为你使它成为json对象的一部分费用 – 2014-09-20 08:02:55

回答

0

你的工厂会是这样

admin.factory('expenseFact', ['$http', function($http) { 
    return { 
     getExpenseList: function() { 
      var expense = {}; 
      this.expenses = $http({ 
       headers: { 
        'Content-Type': 'application/x-www-form-urlencoded' 
       }, 
       method: "GET", 
       url: base_url + "rest/expenses" 
      }); 

      return this.expenses; 
     } 
    } 
}]); 

,你可以从控制器相同的方式调用它,它不会自动调用它。 btw我推荐使用承诺。

下面

是相同的代码使用承诺的

admin.factory('expenseFact', ['$http', '$q'. function($http, $q) { 
    return { 
     getExpenseList: function(){ 
      var deferred = $q.defer(); 
      $http({method: 'GET', 
       headers: { 
        'Content-Type': 'application/x-www-form-urlencoded' 
       } 
       }). 
      then(function(response) { 
       deferred.resolve(response.data); 
      }, function(response) { 
       deferred.reject(response.status) 
      }); 

      return deferred.promise; 
     } 
    } 
}]); 
+0

其中是url?我想尝试承诺的事情。但我不知道你在哪里把这个网址 – 2014-09-20 08:32:23

0

你需要一次获得费用在出厂的时候被加载的第一次;

admin.factory('expenseFact', ['$http', function($http) { 
    var expenses = null; 
    $http({ 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded' 
      }, 
      method: "GET", 
      url: base_url + "rest/expenses" 
    }).success(function (exp) { 
     expenses = exp; 
    }); // get the expenses when the factory is loaded 

    return {expenses: expenses}; 
}]); 

这里做的事情是,它使得从工厂expenses回报是指一次性Ajax调用来获取费用。

+0

这不起作用。 – 2014-09-20 09:47:50

+0

@AmitavRoy为什么?控制台上的错误是什么? – Ashesh 2014-09-20 10:24:58