I have a function to get the current company code which I need to store on localstorage and use it in the rest of API calls. so until the value of this company code is not retrieved, I shouldn't make the API calls. This is how I get the company code
currentDivision = function() {
var q = $q.defer();
var division = window.localStorage.getItem("CurrentDivision");
if(division){
return q.resolve(division);
}
else{
var url = this.fooApi + "current/Me?$select=CurrentDivision";
$http.get(url)
.success(function(data) {
division = data.d.results[0].CurrentDivision;
window.localStorage.setItem("CurrentDivision", division);
return q.resolve(division);
})
}
return q.promise;
}
and this is how I try to call the rest of the API calls after making sure the current division is retrieved successfully:
$scope.openModal = function() {
$scope.modal.show().then(function() {
currentDivision().then(function(){
fooServices.getData().then(function() {
$scope.closeModal();
}, function(reason) {
// handle the error
$scope.showAlert(reason);
$scope.closeModal();
})
});
})
}
but as I try this on, I get this error message: TypeError: Cannot read property 'then' of undefined
You should always return q.promise. Remove the return in:
if (division) {
return q.resolve(division);
}
I.e.:
var q = $q.defer();
// ...
if (division) {
q.resolve(division);
} else {
//...
}
return q.promise;
In this way you are returning already resolved promise, which calls then immediately.
Try this:
if (division) {
return $q.when(division);
}
And improve your code:
currentDivision = function () {
if (division) {
return $q.when(division);
}
var url = this.fooApi + "current/Me?$select=CurrentDivision";
return $http.get(url).then(function (data) {
division = data.d.results[0].CurrentDivision;
window.localStorage.setItem("CurrentDivision", division);
return division;
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With