Search code examples
angularjsangular-http

Angular post method


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.


Solution

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