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

user3037814
  • 143
  • 3
  • 16

2 Answers2

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

Community
  • 1
  • 1
ryeballar
  • 29,658
  • 10
  • 65
  • 74
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());
        }
    }
]);
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80