AngularJS$http.get()在返回布尔的本地函数中



我是AngularJS的新手。

我在我的一个angularjs控制器中有一个本地函数,当我做一些动作时,我会调用它。提前谢谢!

$scope.AddUser = () => {
if(validateUser()) {
doSomething();
}
}
function validateUser() {
//-- This one works
if(....) {
return false;
}
//-- Even after returning false, it still reaches 
//-- the last line which is return true therefore executing the 
//-- doSomething() function
$http({
....
....
}).then(function success(response){
if(response.data) {
return false;
}
},function error(response) {
return false;
});
return true;
}

$http调用是异步的,因此函数在获得http-get:的结果之前到达此行

return true;

您需要修改validateUser以返回承诺:

function validateUser() {

return $http({
....
....
}).then(function success(response){
if(response.data) {
return false;
}
},function error(response) {
return false;
});

}

并像这样使用:

validateUser().then((result)=> {
if (result) doSomething();
})

最新更新