Sunday, 22 May 2016

Caching JSON with AngularJS




I'm loading JSON in my controller, changing routes the JSON gets reloaded. I would like to cache it.



var sampleApp = angular.module('sampleApp', [
'ngRoute',
'sampleAppControllers',
]);

var sampleControllers = angular.module('sampleControllers', []);


sampleControllers.controller('PostsCtrl', ['$scope', '$http',
function($scope, $http) {
// Should be loaded only on app load
$http.get('http://example.org/source.json').success(function(data) {
$scope.posts = data;
});

$scope.orderProp = 'id';
}]);



I tried using .constant, but couldn't get it work:



sampleApp.constant('myCache', ['$http', 
function($http) {
$http.get('http://example.org/source.json').success(function(data) {
return data;
});
}]);


sampleControllers.controller('PostsCtrl', ['$scope', 'myCache',
function($scope, myCache) {
$scope.posts = myCache;
$scope.orderProp = 'id';
}]);


I'm looking for a way to load JSON on app start, and use it in controllers.


Answer




That's what Angular Services are for - load the data inside the service instead of inside the controller, and have the controller access this data. Services are instantiated once in the lifetime of an app, which is exactly what you want here.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...