数据存储使用$ resource,$ cacheFactory和errorHandlingDirective

时间:2016-02-13 01:16:20

标签: angularjs angular-resource angular-directive cachefactory

学习AngularJS并尝试使用数据存储创建SPA REST服务器。为了尽可能减少流量,我想 尽可能缓存数据。在错误响应的情况下 从服务器,我想处理所有回调的一个通用指令。这将允许我以一种常见的方式跨多个控制器执行指令。

除了$ emit和/或$ broadcast之外,这篇文章都有效 解雇指令等待$的事件。如果它正在工作,则指令中的模板将具有错误描述,并在isError变为true时显示在HTML页面上。至少那是我现在的想法......

Plunker

我的示例HTML文件:

<!DOCTYPE html>
<html ng-app="app">

<head>
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16">    </script>
<script data-require="angular-resource@1.2.14" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular-resource.js"></script>
<!--script src="app.js"></!--script-->
</head>
<body ng-controller="MainCtrl">
<h1>Hello Plunker!</h1>
{{data}}
<br />
<br />
isError: <error></error>

<br /><br />
Cached Data: {{dataCache}}

<br /><br />
<button ng-click="getData()">Data Callback</button>
<br /><br /><br />
<button ng-click="getError()">Callback Error</button>
<br /><br /><br />
Cache Info: {{oDataServiceInfo}}<br />
<button ng-click="resetCache()">Reset Cache</button>

</body>
</html>

我的示例控制器:

var app = angular.module('app', ['ngResource']);

app.controller('MainCtrl', ['$scope', '$rootScope', 'loDataService', function ($scope,$rootScope, loDataService) {

    $scope.getData = function () {
        loDataService.getData(function (data) {
            $scope.dataCache = loDataService.lCache
            $scope.oDataServiceInfo = loDataService.oInfo;
            $scope.data = data;
        }, function (error) {
            console.log(error);
        })
    };

    $scope.getError = function () {
        loDataService.getError(function (data) {
            $scope.dataCache = loDataService.lCache
            $scope.oDataServiceInfo = loDataService.oInfo;
            $scope.data = data;
        }, function (error) {
            $rootScope.$broadcast("resourceError", error);

            console.log(error);
        })

    };

    $scope.resetCache = function () {
        loDataService.resetCache();
        $scope.oDataServiceInfo = loDataService.oInfo;
    };


}]);

我的示例数据存储:

app.factory('loDataService', ['$resource','$cacheFactory','$rootScope', function ($resource, $cacheFactory, $rootScope) {
    var dbcCache = $cacheFactory('loDataService');
    var oDBC = $resource('/', {},
        {
            'GetError': { url:'nonExistingConnection',method: 'GET' },
            'GetData': { url: 'sampleData.json', method: 'GET', isArray: false }
        });

    return {
        lCache: true,
        oInfo: {},
        resetCache: function () {
            dbcCache.removeAll();
            this.oInfo = dbcCache.info();
        },
        getData: function (callback, callbackError) {
            _this = this;
            var markets = dbcCache.get('Markets');
            if (!markets) {
                // fetch from server
                _this.lCache = false;
                oDBC.GetData(function (response) {
                    // store in cache
                    dbcCache.put('Markets', response.Markets);
                    _this.oInfo = dbcCache.info();
                    // return response
                    callback(response.Markets);
                },
                    function (error) {
                        // oh no, what went wrong?
                        callbackError(error);
                    });
            } else {
                // return the cache
                _this.lCache = true;
                callback(markets);
            }
        },
        getError: function (callback, callbackError) {
            _this = this;
            var marketsX = dbcCache.get('MarketsX');
            if (!marketsX) {
                // fetch from server
                _this.lCache = false;
                oDBC.GetError(function (response) {
                    // store in cache
                    dbcCache.put('MarketsX', response.Markets);
                    // return response
                    callback(response.Markets);
                },
                    function (error) {
                        // oh no, what went wrong?
                        callbackError(error);
                        $rootScope.$broadcast("resourceError", error);
                    });
            } else {
                // return the cache
                _this.lCache = true;
                callback(marketsX);
            }
        }
    }

}]);

我的样本指令:

app.directive("resourceError", ['$rootScope', function ($rootScope) {
    return {
        restrict: 'E',
        template: '<div class="alert-box alert" ng-show="isError" >Error!!!</div>',
        link: function (scope) {
            $rootScope.$on("resourceError", function (event, error) {
                scope.isError = true;
                console.log(error);
            })
        }
    }
}]);

这是我的“sampleData.json”文件。

{
    "Markets": [{
        "id": 1,
        "name": "Downtown",
        "eventday": "1/1/1991",
        "active": true
    }, {
        "id": 2,
        "name": "County",
        "eventday": "2/2/1991",
        "active": true
    }, {
        "id": 3,
        "name": "Beach",
        "eventday": "3/3/1991",
        "active": false
    }]
}

有什么想法吗?

0 个答案:

没有答案
相关问题