I have a scenario where I need to load data from local files using the global loadJSON
function (though it's not mandatory, it's recommended).
Once the data is loaded from all the documents, I want to print the string 'i ve loaded'
.
The issue arises when I start using data from the 'x' service before it is fully loaded into memory from the files.
How can I ensure that I wait for the data to be loaded before proceeding with rendering the pages and executing other tasks?
It seems like using $q
might be the solution, but how should I implement it?
function loadJSON(file, callback) {
var doc = new XMLHttpRequest();
doc.overrideMimeType("application/json");
doc.open('GET', file, true);
doc.onreadystatechange = function () {
if (doc.readyState == 4 && doc.status == "200") {
callback(JSON.parse(doc.responseText));
}
};
doc.send(null);
}
angular
.module('msApp')
.factory('service.x', [
function () {
var _database = {};
return {
get: function (k1, k2) {
return _database[k1][k2];
},
load: function (list, callback) {
var length = list.length;
var loaded = 0;
function addToDB(name) {
var url = './assets/{0}.json'.format(name);
loadJSON(url, function (json) {
_database[name] = json;
loaded++;
if (length === loaded && callback) callback();
});
}
for (var i = 0; i < list.length; i++) {
addToDB(list[i]);
}
}
};
}
]);
angular
.module('msApp', [])
.run([
'$rootScope',
'service.x',
function ($rootScope, x) {
x.load($rootScope.services, function () {
console.log('i ve loaded')
});
}
])
.config(function ($routeProvider) {
$routeProvider
.when('/sign', {
templateUrl: '../views/sign.html',
controller: 'signCtrl'
})
.when('/a', {
templateUrl: '../views/a.html',
controller: 'aCtrl'
.otherwise({
redirectTo: '/signin'
});
});