Json question


#1

HI, first of all i’m completely new on this one.
I’m creating an app that use json file to store data. Is it possible to update the json file, like download a new json file from a server then replace the old one inside the app ? is there such a thing like that ?

also i’m using this code to read json file

.factory('Lessons', function($q, $timeout, $http) {

    .factory('Lessons', function($q, $timeout, $http) {
   var lessons = {
        fetch: function(callback) {    
            var deferred = $q.defer();
            $timeout(function() {
                $http.get('js/lessons.json').success(function(data) {
                    deferred.resolve(data);
                });
            }, 

    30);
                return deferred.promise;
            }, 
    		//index lookup
    		get: function(lessonsId) {
    			return lessons[lessonsId];
    		}
        };
       return lessons;
    })

the result is my app became laggy and the page change animation doesn’t work. also the back button doesn’t work like if i just put the json array inside the factory. is there something wrong with my code ?


#2

Hey, welcome to the forum ! :smile:

You can totally use a JSON file to store / retrieve datas, but depending on the size of the JSON file, it can take some time to get it.

Btw, why do you use the $timeout var ?

I don’t know if it’s the good way to do, but here is how I do it. For exemple, for users, I have a UserService like this :

.factory('UserService', function($http, $q, $window) {
	return {
		get: function() {
			var deferred = $q.defer();
			$http
				.post(api_url + '/mon-compte')
				.success(function(data, status) {
					deferred.resolve(data);
				})
			return deferred.promise;
		},
	}
});

And in my UserController, I use it this way :

controller('UserController.index', ["$scope", "$state", "$ionicLoading", "$window", "UserService", "$ionicPopup",
		function($scope, $state, $ionicLoading, $window, User, $ionicPopup) {
			$ionicLoading.show({
				template: '<i class="ion-loading-c"></i> &nbsp;Chargement en cours…',
			});
			User.get().then(function(result) {
				$scope.user_account = result;
				$ionicLoading.hide();
			})
		}
	])

And so, the ionicLoading shows up while I’m fetching datas, and hide when I get something