Reputation: 75
I have an Ionic application, that I'm trying to return data from inside a closure. The console is showing everything properly, but I can't seem to get the data to return properly. I've tried a few different variations with no luck.
$scope.callbackMethod = function (query) {
//var ritems= new Array();
var ritems;
Inventory.search(query, $scope.currentUser.token, $scope.currentUser.user_id, function(response) {
//console.log(JSON.stringify(response));
if(response.success == true)
{
$ionicLoading.hide();
$scope.requestmodal.hide();
console.log(response.items);
ritems= response.items;
}
else
{
$ionicLoading.hide();
//console.log(response.message);
return $scope.errorMessage = response.message;
}
});
console.log(ritems);
return ritems;
};
and also this:
$scope.callbackMethod = function (query) {
//var ritems= new Array();
var ritems = Inventory.search(query, $scope.currentUser.token, $scope.currentUser.user_id, function(response) {
//console.log(JSON.stringify(response));
if(response.success == true)
{
$ionicLoading.hide();
$scope.requestmodal.hide();
console.log(response.items);
return response.items;
}
else
{
$ionicLoading.hide();
//console.log(response.message);
return $scope.errorMessage = response.message;
}
});
console.log(ritems);
return ritems;
};
the json that is returned to the script is:
{"success":true,"items":[{"id":"1","0":"1","name":"Product 1","1":"Product 1","ref_id":"","2":""},{"id":"2","0":"2","name":"Product 2","1":"Product 2","ref_id":"","2":""}],"message":""}
Any thoughts? Much appreciated!!
Upvotes: 0
Views: 297
Reputation: 569
You can follow this approach to solve your problem
var cbm = function (query) {
var defer = $q.defer();
Inventory.search(query, $scope.currentUser.token,$scope.currentUser.user_id, function(response) {
if(response.success == true)
{
$ionicLoading.hide();
$scope.requestmodal.hide();
defer.resolve(response.items) ;
}
else
{
$ionicLoading.hide();
defer.reject(response.message);
}
});
return defer.promise;
};
and while calling you can then call your callbackMethod like
$scope.callbackMethod = function (query){
return cbm(query).then(function(data){ return data;});
}
Upvotes: 1