$ http.get cache false无效

时间:2016-03-07 19:12:09

标签: angularjs

我正在使用此代码调用该方法,但它仍然保留缓存而不刷新屏幕上的数据

(function () {
    'use strict';

    app.controller('categoryController', ['$http', '$location', 'authService', 'ngWEBAPISettings', categoryController]);

    ////categoryController.$inject = ['$location']; 

    function categoryController($http, $location, authService, ngWEBAPISettings) {
        /* jshint validthis:true */

        //Creating headers for sending the authentication token along with the system.
        var authheaders = {};
        authheaders.Authorization = 'Bearer ' + authService.getToken();

        //ForDate
        var d = new Date();

        var vm = this;
        vm.title = 'Category';
        ////debugger;

        ////Vadiable for Grid
        vm.Category = [];

        ////Vadiable for Adding
        vm.category = {
            CategoryID: 0,
            CategoryName:"",
            CreatedOn:d,
            UpdatedOn:d
        };
    ////Vadiable for Editing
    vm.editCategory = {};

    vm.getCategory = function () {
        ////debugger;

        ////authheaders.cache = false;


        var config = {
            headers: {
                'Authorization': authheaders.Authorization
            },
            cache: false,
        };


        //For Grid
        $http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Categories", config)
        .then(function (respose) {
            //success
            ////debugger;
            angular.copy(respose.data, vm.Category);
            ////debugger;
            //var i = 2;
            ////debugger;
        }, function (response) {
            //failure
            ////debugger;
        }).finally(function () {
            ////debugger;
            //finally
        }
        );
    }

    vm.add = function ()
    {
        ////authheaders.Content-Type="application/x-www-form-urlencoded";
        ////debugger;

        vm.category.CreatedOn = d;
        vm.category.UpdatedOn = d;

        $http.post(ngWEBAPISettings.apiServiceBaseUri + "api/Categories", JSON.stringify(vm.category), { headers: authheaders })
        .then(function (repose) {
            ////success
            ////debugger;
            vm.Category.push(repose.data);
            alert('Category has been addded successfully');
            $('#addModal').modal('hide');
        }, function (response) {
            ////failure
            ////debugger;
            alert('An error has been occurred while adding the data');
        }).finally(function () {
            vm.category = {};
        });
    }

    vm.edit = function (id) {
        ///debugger;
        ////alert(id);
        $('#btnSubmit').html('Update');

        $("#btnSubmit").removeAttr("ng-click");
        $("#btnSubmit").attr("ng-click", "vm.edit()");

        $('#addModal').modal('show');

    }
    vm.delete = function (id) {
        ////debugger;
        alert(id);
    }


    activate();
    function activate() { vm.getCategory(); }

}
})();

这是html

            <h1>{{vm.title}}</h1>

           <div id="addModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel">
                <div class="modal-dialog" role="document">
                 <div class="modal-content">
             <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="gridSystemModalLabel">Add Category</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="control-label col-md-3">Category Name</label>
                            <input class="form-control col-md-9" type="text" name="txtcategoryname" id="txtcategoryname" maxlength="200" ng-model="vm.category.CategoryName" required />
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btnSubmit" class="btn btn-primary" ng-disabled="!vm.category.CategoryName"  ng-click="vm.add()">Add</button>
            </div>
               </div>
              </div>
       </div>
              <div class="row">
    <div class="col-md-12 col-md-offset-10">
        <a href="" onclick="openAddModal()"><span class="fa fa-plus fa-200px"></span> Add New Record</a>

    </div>
</div>
<table class="table table-responsive table-hover">
    <thead>
        <tr>
            <th>Category Name</th>
            <th>Created On</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="cat in vm.Category">
            <td style="vertical-align:middle">{{cat.categoryName}}</td>
            <td style="vertical-align:middle">{{cat.createdOn | date:'dd-MMM-yyyy' }}</td>
            <td>
                <input type="button" class="btn btn-sm btn-primary" ng-click="vm.edit(cat.categoryID)" value="Edit" />
                <input type="button" class="btn btn-sm btn-primary" ng-click="vm.delete(cat.categoryID)" value="Delete" />
            </td>
        </tr>
    </tbody>
</table>
<script type="text/javascript">
    function openAddModal() {
        $('#addModal').modal('show');
        $('#btnSubmit').val('Add');
    }
</script>

这里是从

调用的
function activate() { vm.getCategory(); }

3 个答案:

答案 0 :(得分:0)

它会为所有获取请求禁用缓存。

myApp.config([
            // Diable IE Cache for $http.get requests
            '$httpProvider', function ($httpProvider) {
                // Initialize get if not there
                if (!$httpProvider.defaults.headers.get) {
                    $httpProvider.defaults.headers.get = {};
                }
                // Enables Request.IsAjaxRequest() in ASP.NET MVC
                $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

                // Disable IE ajax request caching
                $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
            }
        ]);

答案 1 :(得分:0)

根据此Angular链接https://docs.angularjs.org/api/ng/service/默认情况下禁用$ http缓存。检查缓存中是否有某个全局设置,并在需要时禁用。

还可以通过在querystring中添加datetime参数来尝试此解决方案。 Destroying AngularJS $Http.Get Cache

答案 2 :(得分:0)

此代码适合我

app.config(['$httpProvider', function ($httpProvider) {
    //initialize get if not there
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }

    //disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
    // extra
    $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
    $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);