我正在尝试从服务和一个直接调用的同步两个回调。 (这是旧代码所以请忽略代码质量)
if($scope.newUser.password == $scope.newUser.password2)
{
// search for the user to see if it already exists
UserValidateService.findUserByEmail($scope.newUser.username, $scope.newUser.email, function(user){
console.log(user);
if(user[0]) {
alert('email Id already exists ******');
return false;
}
}).then(function(){
$http.get("/api/user/"+$scope.newUser.username)
.success(function(newUser) {
// if user does not exist, create it new
if(newUser.length == 0) {
$http.post("/api/user", $scope.newUser)
.success(function(newUser){
if(newUser == null)
alert("Unable to register user");
else
$location.path( $scope.newUser.username+"/home" );
});
}
else
{
alert("User already exists");
}
});
});
}
else
{
alert("Passwords must match. Try again");
}
服务:
app.factory('UserValidateService', function($http){
var findUserByEmail = function (user, email, callback) {
$http.get("/api/user/"+user+"/email/"+email)
.success(callback);
};
return {
findUserByEmail: findUserByEmail
};
});
错误:
TypeError: Cannot read property 'then' of undefined
at h.$scope.register (user.js:118)
at angular.js:10567
at angular.js:18627
at h.$eval (angular.js:12412)
at h.$apply (angular.js:12510)
at HTMLButtonElement.<anonymous> (angular.js:18626)
at HTMLButtonElement.jQuery.event.dispatch (jquery.js:5095)
at HTMLButtonElement.elemData.handle (jquery.js:4766)
任何请让我在哪里出错或如何使这段代码同步,即致电
答案 0 :(得分:0)
您的UserValidateService
没有返回承诺,它使用来自$http
成功方法的回调。这是应该避免的anti-pattern。
转换工厂以从$http
服务返回承诺:
app.factory('UserValidateService', function($http){
var findUserByEmail = function (user, email) {
return $http.get("/api/user/"+user+"/email/"+email)
};
return {
findUserByEmail: findUserByEmail
};
});
然后使用promise的.then
方法执行回调功能。
var promise = UserValidateService
.findUserByEmail($scope.newUser.username,
$scope.newUser.email);
var derivedPromise = promise.then ( function(response){
console.log(response.user);
if(response.user[0]) {
alert('email Id already exists ******');
});
//return response for chaining
return response;
});
后续操作可以链接derivedPromise
。