简体   繁体   中英

Ionic Angular Closure for trying to return json data

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!!

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;}); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM