Below is the controller code that I am using:
.controller('SponsorsCtrl', function ($scope, Sponsors, $http) {
$scope.$on('$ionicView.enter', function () {
Sponsors.all($http).then(function (data) {
$scope.sponsors = data;
var check = "check";
})
});
})
The reason for utilizing "then" is because I am dealing with an asynchronous object. However, there is also a scenario where I may receive a synchronous object through this service: (function(){ angular .module('sponsors.services', []) .factory('Sponsors', Sponsors);
Sponsors.$inject = [];
function Sponsors() {
var service = {
all: all,
allServer: allServer,
allLocal: allLocal,
get: get,
getTimeStamp: getTimeStamp
};
return service;
function all($http) {
var timeDifference = (Date.now() - this.getTimeStamp());
if (timeDifference < 600000) {
return this.allLocal();
}
else {
return this.allServer($http);
}
}
function allServer($http) {
return $http.get("http://dream16backend.azurewebsites.net/api/dream16/sponsors")
.then(function (resp) {
//Set localstorage, create timestamp and return the data
window.localStorage.setItem('sponsors', resp.data);
window.localStorage.setItem('sponsorsTimeStamp', Date.now());
var bla = JSON.parse(window.localStorage.getItem('sponsors'));
return bla;
}, function(err) {
console.log('ERR', err);
});
}
function allLocal() {
return JSON.parse(window.localStorage.getItem('sponsors'));
}
function get(adressId) {
for (var i = 0; i < sponsors.length; i++) {
if (sponsors[i].id === parseInt(sponsorId)) {
return sponsors[i];
}
}
return null;
}
function getTimeStamp() {
return window.localStorage.getItem('sponsorsTimeStamp');
}
}
})(); In this setup, only the async call (function allServer) is functioning properly, but the sync call is failing due to:
Sponsors.all(...).then is not a function
I attempted to resolve this issue by moving the "then" functionality to the all function in the service. This change allows the sync call (function allLocal) to work, but now the async call fails. The else condition now looks like this:
else {
this.allServer($http).then(function (data) {
return data;
})
}
And the controller has been adjusted accordingly:
.controller('SponsorsCtrl', function ($scope, Sponsors, $http) {
$scope.$on('$ionicView.enter', function () {
$scope.sponsors = Sponsors.all($http);
var check = "check";
});
})
I have verified that the call itself is functional (verified via test variable "bla"). Additionally, it seems that the controller executes var check = "check"; before running the async code. What could be the issue here?