angularjs - 在 angular.js 中缓存并设置范围值

标签 angularjs angularjs-scope

我有一个多标签应用程序,有两个单独的 Controller 。

当输入任一选项卡时,我需要点击一个 API。初始点击后响应不会更新,因此在后续访问该选项卡时无需再次点击它。

我的问题是缓存 API 响应并将其设置为范围变量的正确方法是什么。

目前,我有一个这样的帮助功能设置

var setAndCache = function(scope, cacheFactory, cacheKey, cacheValue) {
  scope[cacheKey] = cacheValue;
  cacheFactory.put(cacheKey, cacheValue);
};

像这样的缓存工厂设置
factory('TabData', function($cacheFactory) {
  return $cacheFactory('tabData');
}).

注入(inject)到每个 Controller 中
controller('TabOne', function($scope, $http, TabData) {

  var setupCache = function(response) {
    setAndCache($scope, TabData, 'tabOneData', response);
  };

  if (!TabData.get('tabOneData')) {
    $http.get('/path/to/api')
    .success(function(response) {
      setupCache(response);
    });
  }
  else {
    setupCache(TabData.get('tabOneData'));
  }

这很好用,但感觉……很脏。
有没有更好的方法来实现同样的目标?

最佳答案

我自己一直在处理资源缓存。到目前为止,这是我的做法。

我从一个 cacheManager 服务开始:

app.factory('cacheManager', function($cacheFactory) {
    var cache = $cacheFactory('resource');

    return {

    /**
     * This will handle caching individual resource records
     * @param  CacheId string where we expect this to be stored in the cache
     * @param  Resource resource The resource object that we want to get
     * @param  Object param An object of params to pass to resource.get
     * @param  Function callback
     * @return resource object
     */
    fetchResource: function(cacheId, resource, params, callback) {
        var result = cache.get(cacheId);

        // See if we had a valid record from cache
        if(result) {
            console.log("cache hit: " + cacheId);
            callback(result);
            return result;
        } else {
            console.log("cache miss: " + cacheId);
            result = resource.get(params, function(response) {
                if(response.error) {
                    // We don't have a valid resource, just execute the callback
                    callback(response);
                    return false;
                }
                console.log("putting resource in cache");
                cache.put(cacheId, response);
                callback(response);
            });
            return result;
        }
    },
    <snip update/delete methods, etc>

然后在我的 Controller 中,我注入(inject) cacheManager 服务和我的项目资源(例如),然后可以执行以下操作:
$scope.data = cacheManager.fetchResource('project.' + $scope.id, Project, {id: $scope.id}, function(response) {
        ...
});

我喜欢这让我的 Controller 保持清洁。

我知道在您的情况下您直接使用 $http 而不是资源,但可以使用相同的方法。我个人建议将尽可能多的逻辑抽象到缓存包装服务中,并尽量减少每个 Controller 的开销。

更新:

正如下面在评论中提到的,有一个更简单的资源缓存值得一看。我最初是从这个示例开始的,然后将它构建到我现在使用的上面。

angularjs: how to add caching to resource object?

关于angularjs - 在 angular.js 中缓存并设置范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15755215/

相关文章:

javascript - Angularjs,如何在 Controller 中单击按钮时重置指令变量?

javascript - 使用 ControllerAs 语法与服务变量绑定(bind)而不使用 $scope?

angularjs ng-paste 不更新模型值

javascript - Angular.js 值未保存在文本框中的范围内

javascript - 从 JSON 获取数据时不显示任何内容

javascript - 如何处理 $interval is not a function error in angularjs?

javascript - Angular.js - 根据 View 显示链接

javascript - AngularJS 无法连接 Controller 实例

javascript - ng-model 不会在文本过滤器的单个按键上重新计算数组长度

jquery - Angular - 动态设置 html img 宽度和高度