Kiddo
Kiddo

Reputation: 1175

Angular Cache $resource Result

I'm looking for a way to cache language translation in angular js application.

In the application, there are many form that need translation. To get the available languages, I use $resource to get them from our Language API.

First, I create an empty array of languages on application run()

angular
  .module('admin', [])
  .run(['$rootScope',
    function($rootScope) {
      $rootScope.languages = [];
    }
  )
;

Then I create a service to handle translation and language query

angular
  .module('admin')
  .factory('Utils', ['$rootScope', 'Language',
    function($rootScope, Language) {
      var utils = {};

      utils.getLanguages = function() {
        if ($rootScope.languages.length > 0) {
          return $rootScope.languages;
        }

        var languages = Language.query(function(data) {
          $rootScope.languages = data;
        });

        return languages;
      }

      return utils;
    }
  )
;

and in the controller

angular
  .module('admin')
  .controller('CategoryController', ['$scope', 'Utils',
    function($scope, Utils) {
      $scope.languages = Utils.getLanguages();
    }
  ])
;

That's the way I cache the $resource result. What do you think about this solution? Is it ok to cache in $rootScope?

The reason I want to cache the result because I need the languages in most of the controller, so I don't want to make request for the Language API everytime I access a new state.

Upvotes: 0

Views: 121

Answers (1)

Chandermani
Chandermani

Reputation: 42669

There as some improvement that you can do with your implementation.

You don't need to use $rootScope for saving language and then exposing it through a service. You can very well use a service and cache the results in the service.

Something like this should be better option

angular.module('admin')
    .factory('LanguageCache', ['$rootScope', 'Language',
function ($rootScope, Language) {
    var service = {};
    var cache;

    service.getLanguages = function () {
        if (cache) {
            return cache;
        }

        var languages = Language.query(function (data) {
            cache = data;
        });

        return cache;
    }

    return service;
});

This way the language cache will be available for services that want it. It will not pollute the global $rootScope object.

Upvotes: 1

Related Questions