【发布时间】:2014-09-06 04:10:58
【问题描述】:
我正在使用工厂配方从控制器调用方法,这是工厂定义。
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。知道我缺少什么吗?
【问题讨论】:
-
你的函数没有返回任何东西,第二个你正在做 asyc 调用,所以你的函数将在 ajax 请求完成之前返回
-
正如帕特里克所说,异步函数不会返回这样的值,要么返回承诺,要么使用回调。
标签: javascript angularjs