0

I am using a factory recipe to call a method from controller, here is the factory definition.

app.factory('AccountService', function ($http){
    var factory = {};

    factory.getAuthenticate = function (credentials) {
        $http({
            method: 'post',
            url: '/api/login',
            data: credentials
        }).success(function (data, status, headers, config){
            return true;
        }).error(function (data, status, headers, config){
            return false;
        });
    }

    return factory;
});

When I call getAuthenticate method from one of my controller,

app.controller('DefaultController', function ($scope, $location, AccountService){
    $scope.login = function(){
        alert(AccountService.getAuthenticate($scope.credentials));
        // if(AccountService.getAuthenticate($scope.credentials)) {
        //     $location.path('/dashboard');
        // }
    }
});

It always returns undefined instead of true or false based on http calls. Any idea what I am missing?

Blackhole
  • 20,129
  • 7
  • 70
  • 68
Dipendra Gurung
  • 5,720
  • 11
  • 39
  • 62
  • 3
    your function doesnt return anything for one, second you are doing asyc calls so your function is going to return before the ajax request is done – Patrick Evans Sep 06 '14 at 04:15
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Patrick Evans Sep 06 '14 at 04:16
  • As Patrick says, an async function won't return a value like that, either return the promise or use a callback. – Mohammad Sepahvand Sep 06 '14 at 04:17

1 Answers1

-1

$http method automatically return a promise. so you should have to handle this in a controller.your code should be like this:

    app.factory('AccountService', function ($http){
        var factory = {};

        factory.getAuthenticate = function (credentials) {
            return $http({
                method: 'post',
                url: '/api/login',
                data: credentials
            });
        };

        return factory;
    });



app.controller('DefaultController', function ($scope, $location, AccountService){
    $scope.login = function(){
        AccountService.getAuthenticate($scope.credentials)
            .success(function (response) {
                alert('Everything went better than expected :)');
                $location.path('/dashboard');
            })
           .error(function (error) {
                alert(error);

            });
    };
});
Mukund Kumar
  • 21,413
  • 18
  • 59
  • 79
  • Your callbacks should be abstracted out of the controller and placed into the factory. You should only do data binding inside of your controller after you made your call using the service. – tjacks3 Oct 16 '15 at 15:00