AngularJS - 如何刷新cacheFactory中的数据

时间:2015-05-07 11:49:36

标签: javascript angularjs

我正在使用$cacheFactory,我喜欢它,因为它会不会一直调用服务数据来提高性能。但我怀疑是更新现有数据,如何更新$cacheFactory数据

service.query = function(queryCriteria) {
  var deferred = $q.defer();
  var req = {
    method: 'GET',
    url: BASE_URL + '/ticketCategories' + '?' + ApplicationUtil.parseQueryCriteria(queryCriteria),
    headers: {
      'Authorization': APP_CONSTANTS.STRATAGIES.BEARER + ' ' + ApplicationStorage.getJwtToken()
    },
    cache: true
  };
  var cache = $cacheFactory(Math.random());
  var data = cache.get("ticketCategories");
  if (!data) {
    $http(req).then(function(payload) {
      deferred.resolve(payload.data);
      cache.put("ticketCategories", payload.data);
    }, function(reason) {
      Logger.error(reason, 'Error querying ticket categories');
      deferred.reject(reason);
    });
  } else {
    return data;
  }
  return deferred.promise;
};

1 个答案:

答案 0 :(得分:1)

使用您的代码的示例实现可能如下所示。

var cache = $cacheFactory(Math.random());

service.query = function(queryCriteria) {
    var deferred = $q.defer();
    var req = {
        method: 'GET',
        url: BASE_URL + '/ticketCategories' + '?' + ApplicationUtil.parseQueryCriteria(queryCriteria),
        headers: {
            'Authorization': APP_CONSTANTS.STRATAGIES.BEARER + ' ' + ApplicationStorage.getJwtToken()
        },
        cache: true
    };
    var data = cache.get("ticketCategories");
    if (!data) {
        $http(req).then(function(payload) {
            deferred.resolve(payload.data);
            cache.put("ticketCategories", payload.data);
        }, function(reason) {
            Logger.error(reason, 'Error querying ticket categories');
            deferred.reject(reason);
        });
    } else {
        return data;
    }
    return deferred.promise;
};

service.refresh = function (queryCriteria) {
    // removes all cached entries
    cache.removeAll();
    // force reload, still returns the promise
    return service.query(queryCriteria);
};