Problem with services and ajax call


#1

Hello guys, im new en Ionic and i have a little problem …

I have this service

angular.module('starter.services', [])

.factory('RecetaService', function($http) {
  return {
    Ultimas: function(){
      return $http.get(service_url('receta/ultimas'))
            .success(function(r) {
              return r;
            });
    }
  };
})

;

The problem is, that $http.get return empty, but i try to alert and length like this “alert(r.length)” it’s has data.


#2

$http is async call. Use $q to defer if you want to return anything from it.


#3

please give me a example with my code


#4

I am sorry for not giving answer in detail. Whenever you are making an asynchronous call, the function might not return anything as it might still be making the call or resolving the call. That’s the reason why your function is returning a null. If you need to return something with these types of call you can always set the asynchronous option false. In your case you can do

angular.module('starter.services', [])
    .factory('RecetaService', function($http) {
      return {
        Ultimas: function(){
          return $http.get({
          async: false,
          url: service_url('receta/ultimas')
        })
        .success(function(r) {
              return r;
         });
     }
  };
})

async false makes your call synchronous. The other way around is to use promises. That’s what I meant by $q. You can read more about promises in here.

Hope this helps