Angular factory ajax调用每个路由更改

时间:2014-09-20 07:52:33

标签: javascript ajax angularjs angular-routing angular-services

我有一个工厂,我有一个函数getExpenseList,它执行ajax调用,查询费用表并给我结果。

现在我有两条路线,1是费用列表,它通过上述功能推动费用,第二条路线是添加。当我进行路线更改并返回列表页面时,再次进行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;
});

2 个答案:

答案 0 :(得分: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;
        }
    }
}]);

你可以用同样的方式从控制器调用它,它不会自动调用它。 顺便说一句,我建议使用承诺。

下面的

是使用promise

的相同代码
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;
        }
    }
}]);

答案 1 :(得分: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调用以获得费用。