user3406754
user3406754

Reputation: 69

Angularjs service response

I am using angularjs to call server method and getting return response. But the problem is that response from the angularjs service is empty to the controller. Consider my code:

testModule.factory('testService', ['$http', function ($http){

    return {
        getResponse: getResponse
    };

    function getResponse(url, data)
    {

        var returnResponse = {};

        $http({

            'url' : url,
            'method' : 'POST',
            'data' : data
        })
        .success(function(response){

            returnResponse = response;
            console.log(returnResponse);  <-- here it prints the object with data inside.
        });

        console.log(returnResponse);  <-- here it prints empty value for returnResponse.

        return returnResponse;
    }
}]);

as describe in the code the problem is that outside of success function object get null or empty value. Please suggest something. Thanks.

Upvotes: 0

Views: 60

Answers (1)

Sameer Sawla
Sameer Sawla

Reputation: 729

This is because the request that http request that you are calling , is an asynchronous call.

You could think like a different thread going and executing that function and the rest of the function would resume executing normally.

So, as soon as you hit $http(..)

|  .
v  .
|  $http(....)   -----> I would go and get it evaluated asynchronously
V                        When I finish, I will execute anything that lies in success 
|                          callback
v  console.log(...); ------> I will not wait for success to call, that is an async 
|                              operation I will print the value of returnResponse just 
v                                after I hit $http(...), I won't wait for its response

Thus, your console.log(), which is outside the success callback, returnResponse, does not have anything and thus prints undefined or null.

The important concept that you could use here is of Promises or Q. Browse it through. That should be a safe resort to your problem here.

Hope you understood.

Upvotes: 1

Related Questions