-1

I have a few controllers that call the method getData() from a service. In order to not do extra http calls for the same json file, i'm using something like this:

QuizApp.service('quizService', ['$http', function($http) {
    var quizService = {},
        quizData;

    quizService.getData = function() {
        return quizData ? quizData : quizData = $http.get('quiz.json');
    };

    return quizService;
}]);

...but things don't work properly if I do it like that (the data is used to populate a slider and a thumbnail gallery with angular-slick and some problems arise. For now it maybe doesn't matter, I just want to know if the code above makes sense).

On the other hand, if I write getData() like this:

QuizApp.service('quizService', ['$http', function($http) {
    var quizService = {},
        quizData;

    quizService.getData = function() {
        quizData = $http.get('quiz.json');
        return quizData;
    };

    return quizService;
}]);

... which will do various http requests for the same json file (doesn't look like a good practice to me), everything works fine and the slick angular gallery works properly. But not 100% of the times though: kind of randomly things don't work well too (same symptoms. I might describe them but again, I don't think that's the point here)

So, in general, regardless of the context, which one of those versions of getData() looks good and which doesn't and why?

UPDATE

As Mark pointed out, Angular has a built in cache, but it's set to false by default. Here is a post and here is the documentation.

If I cache the result of the http request though I get the same problem (I'm not describing it here) I was getting with my second option, and it has apparently nothing to do with that.

Actually, it seems that if I repeat the http request two times (as in my second snippet of code) things work by chance (90% of the time?).

So, by caching the result, at least I get a consistent result, which means in this case that the slick-angular thing won't work properly (never) and I have to look for a solution somewhere else.

Community
  • 1
  • 1
zok
  • 6,065
  • 10
  • 43
  • 65

1 Answers1

0

Angular $http has a built in cache, which you could make use of here. You can cache all $http requests, which is probably a bad idea, or specific ones.

On a very simple level, this should work for you

quizService.getData = function() {
  return $http.get('quiz.json', {cache: true}).then(quizData => {
    return quizData;
  });
};

You can find out more in the Angular docs for $http

Mark Chorley
  • 2,087
  • 2
  • 22
  • 29