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

3
  • 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}) Commented Aug 20, 2014 at 20:21
  • What returns null? The service? Or do you mean that your error method is executing? Commented Aug 20, 2014 at 20:35
  • Take a look at this answer. it well explained.. stackoverflow.com/questions/25415026/… Commented Aug 20, 2014 at 22:46

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.