1

I have a service that gets data related to the current logged in user from the server, which internally caches the returned user object. The user service:

    var appCache = $cacheFactory.get('appCache');
    var userInfoFromCache = appCache.get('userInfo');

    if (userInfoFromCache) {
        $log.debug("User info cache hit");            
        deferred.resolve(userInfoFromCache);
    } else{
        $log.debug("User info cache miss");
        //do work and get data from server
        appCache.put('userInfo', userInfo);
    }

The service works great. I am calling the user service from multiple places on load such as top navigation and inside the home view. I also call the service in run section of app.js:

.run(function(userService) {
    userService.getUser();
})

Since I am calling the service from multiple places at once, i am ending up with multiple server calls. Is there a way I can setup a lock on the code so that subsequent calls to the userService is served by cache?

5
  • You don't need to (and shouldn't) lock, just return the original promise if a call is already in progress. stackoverflow.com/questions/21125837/… Commented Feb 1, 2016 at 19:36
  • Awesome this helped! I was missing the check for deferred == true. Commented Feb 1, 2016 at 20:05
  • Do you mind posting as answer? I will mark yours as "the" answer. Thanks! Commented Feb 1, 2016 at 20:07
  • 1
    Tempting to collect my nerd points, but it'd basically be a duplicate answer so doesn't really seem worth preserving. Glad I could help anyway! Commented Feb 2, 2016 at 2:37
  • Possible duplicate of Avoid multiple ajax requests angularJS Commented Aug 27, 2018 at 15:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.