1

I am using AngularJS and inside a service I have this:

var fn = {
    test: function() {
        $http.post(...)
        .success(function(response) {
            console.log(response);
            return response;
        })
    }
}

this.testPostCall = function (id) {
   console.log(fn.test());
};

In the controller testPostCall is undefined, in fact in the console the first output that I get is undefined and the second one is the correct JSON response.

Do you know why is undefined inside the controller ? Thanks

2 Answers 2

2

This is because you are doing an asynchronous procedure not a synchronous one. As indicated in the $http documentation:

The $http API is based on the deferred/promise APIs exposed by the $q service

Your code is actually showing the correct behaviour, this is because the fn.test() function does not return anything and therefore evaluates to undefined. If you want to access the data received from your test function, then you have to return the $http.post() itself.

It should be something like this:

var fn = {
    test: function() {
        return $http.post(...);
    }
};

fn.test().success(function(data) {
  console.log(data);
});

EXAMPLE

Sign up to request clarification or add additional context in comments.

Comments

1

Your process is totally Wrong . try this way

Service

var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function () {
    var shinyNewServiceInstance = {
        test: test
    };
    // factory function body that constructs shinyNewServiceInstance
    return shinyNewServiceInstance;

    function test() {
        $http.post(...)
            .success(function (response) {
                console.log(response);
                return response;
            })
    }
});

Controller

myModule.controller('TestController', ['$scope', 'serviceId',
    function ($scope, serviceId) {
        $scope.greeting = 'Hola!';
        $scope.Test = Test;

        function Test() {

            console.log(serviceId.test());
        }
    }
]);

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.