I currently have a situation where multiple controllers are calling the method getData()
from a service. To prevent unnecessary duplicate http calls for the same json file, I have implemented the following approach:
QuizApp.service('quizService', ['$http', function($http) {
var quizService = {},
quizData;
quizService.getData = function() {
return quizData ? quizData : quizData = $http.get('quiz.json');
};
return quizService;
}]);
However, this implementation seems to be causing issues with displaying data on elements like sliders and thumbnail galleries using angular-slick. While there may be some problems at the moment, my main concern is whether the above code structure makes sense.
Alternatively, if I modify the getData()
method as follows:
QuizApp.service('quizService', ['$http', function($http) {
var quizService = {},
quizData;
quizService.getData = function() {
quizData = $http.get('quiz.json');
return quizData;
};
return quizService;
}]);
This second approach results in multiple http requests being made for the same json file, which does not seem ideal practice. However, it does seem to resolve the display issues with the angular-slick gallery. Although not consistently successful, sometimes random issues still occur with this method.
In general, disregarding specific contexts, which version of getData()
seems more appropriate and why?
UPDATE
As mentioned by Mark, Angular has a built-in cache feature, but it is initially set to false. Refer to this post and this documentation for more information.
Even when caching the result of the http request, it seems to present similar issues encountered with the second option. Surprisingly, repeating the http request twice (as seen in the second code snippet) seems to work most of the time.
While caching the result provides consistency, it also means that the slick-angular functionality will never work correctly, prompting the need to explore alternative solutions.