返回未定义值的工厂方法

时间:2014-09-06 04:10:58

标签: javascript angularjs

我正在使用工厂配方从控制器调用方法,这是工厂定义。

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

当我从我的一个控制器调用getAuthenticate方法时,

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

它总是根据http调用返回undefined而不是true或false。知道我错过了什么吗?

1 个答案:

答案 0 :(得分:-1)

$ http方法自动返回一个promise。所以你必须在控制器中处理它。你的代码应该是这样的:

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

            });
    };
});