Saturday 6 January 2018

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 href="https://docs.angularjs.org/guide/services" rel="nofollow">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...