Seeking guidance on the most effective method for fetching data from a local JSON file and managing the response. The plethora of options found on Stack Overflow has left me with conflicting thoughts, as different approaches yield similar results without clear explanations regarding their preferences.
Currently, I have an Angular application that uses a factory to retrieve data from a JSON file. The data is then awaited in the controller before being utilized in the HTML file, as shown below:
Approach 1
Factory:
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile);
}
}
}]);
Controller:
comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {
Info.retrieveInfo().then(function(response) {
$scope.info = response.data;
});
}]);
My uncertainty lies in determining the best time to wait for the response to resolve, or if it holds any significance at all. Considering having the factory return the fulfilled promise and letting the controller fetch the data has crossed my mind. From my perspective, transferring all data retrieval tasks from the controller to the factory seems ideal, but I am unsure if this also includes waiting for the data to be fetched within the factory itself. This dilemma has left me pondering between opting for option 1 or option 2, and I would greatly appreciate insights from seasoned developers!
Approach 2
Factory:
comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';
return {
retrieveInfo: function() {
return $http.get(retrievalFile).then(function(response) {
return response.data;
});
}
}
}]);
Controller:
comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {
Info.retrieveInfo().then(function(response) {
$scope.info = response;
});
}]);
Appreciative of any input or suggestions provided in advance!