-1

I've created a http method in a service. But when i call it, it returns null and i can't figure out why. Here is the method:

 objectResponse.httpCall = function ( sMethodName, postData){

    var rData = null;

    $http({
        dataType: "json",
        type: "POST",
        method: 'POST', 
        url: sMethodName, 
        data: (typeof postData !== "string") ? JSON.stringify(postData) : postData,
        headers: {'Content-Type': 'application/json'}
    })  
    .success(function(data, status, headers, config) {
        rData = data;
      })
    .error(function(data, status, headers, config) {
        rData = null;
      });

    return rData;
}

Thank you.

  • Proper design i would suggest is that your method returns a promise and you chain though the promise. `$http` returns a promise. SO you would do:- `return $http(...).then(function(result) { return result.data }, function(){return null})` and use it as `.httpCall(..).then(function(data){//do the logic here})` – PSL Aug 20 '14 at 20:21
  • What returns null? The service? Or do you mean that your error method is executing? – JeffryHouser Aug 20 '14 at 20:35
  • Take a look at this answer. it well explained.. http://stackoverflow.com/questions/25415026/using-factory-and-http-in-angular-js#answer-25415291 – PSL Aug 20 '14 at 22:46

1 Answers1

2

You can't return from an AJAX call..use a callback:

objectResponse.httpCall = function ( sMethodName, postData, callback){
   ..
   .success(data) {
       callback(data);
}

And pass in the callback:

objectResponse.httpCall(method, data, function(data) {
    console.log(data); //response data
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157