我想我几乎找到了解决问题的方法,但我仍需要进行一些调整。
我有一个Preferences --> Java --> Code Style --> Formatter --> Line Wrapping --> Never join already wrapped lines
,我这样做是为了检查用户是否存在
@RestController
在AngularJs中,我做了类似的事情:
@RequestMapping(value = "/email")
public Boolean getByEmail(@RequestBody String email) {
String userId;
try {
User user = userDao.findByEmail(email);
userId = String.valueOf(user.getId());
LOGGER.info(user.toString());
LOGGER.info(userId);
}
catch (Exception ex) {
LOGGER.info("email does not exist");
return false;
}
LOGGER.info("Email does exist");
return true;
}
我基本上想要做的是找到(function () {
'use strict';
angular
.module('app')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['UserService', '$http' ];
function RegisterController(UserService, $http) {
var vm = this;
vm.register = register;
vm.error="This is a sample Error";
function register() {
testEmail();
console.log(vm.user)
console.log(("email must been verified before this"))
//if the testEmail returns false Create a user else give an error
// vm.dataLoading = true;
// UserService.Create(vm.user)
}
function testEmail(){
console.log("Check email")
console.log(vm.user.email)
console.log($http.post('/email',vm.user.email))
return $http.get('/email',vm.user.email)
}
}
})();
函数返回testEmail
或true
的方式?
答案 0 :(得分:1)
我建议像其中一条评论所说的那样调查异步验证器,但是如果你不喜欢这个选项,这里有更多的信息。
问题在于,由于testEmail函数发出异步ajax请求,因此调用之后的行将在ajax请求完成之前运行。您需要等到请求完成。请参阅以下示例:
function register() {
//test email returns a promise object, you need to wait until it is resolved, passing the response from the server to the callback
testEmail().then(function(response){
//replace this with the appropriate response
if(response.data.valid){
console.log(vm.user)
console.log(("email must been verified before this"))
//if the testEmail returns false Create a user else give an error
// vm.dataLoading = true;
// UserService.Create(vm.user)
}
});
}
答案 1 :(得分:1)
以下是使用异步验证器的示例:
<form name="form" ng-submit="!form.$pending && form.$valid && vm.register()">
<label>Email</label>
<input ng-model="vm.user.email" email-not-used ng-model-options="{ debounce: 500 }" type="text" name="email" />
<div ng-messages="form.email.$error">
<div ng-message="emailNotUsed">User with this email already exists.</div>
</div>
</form>
这里有几点需要注意:
!form.$pending && form.$valid && vm.register()
:这基本上确保您只能提交表单(使用vm.register()
注册用户),如果表单有效且没有待处理的验证(因为异步验证)。ng-model-options="{ debounce: 500 }
:这可以确保每次按键都不会调用验证,但是在最后一次击键后500 ms没有其他活动email-not-used
是下一步中定义的异步验证指令ngMessages
用于显示错误消息app.directive('emailNotUsed', function($http, $q) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.emailNotUsed = function(modelValue, viewValue) {
return $http.get('/email', viewValue).then(function(response) {
return response.data == true ? $q.reject('Email is already used.') : true;
});
};
}
};
});
另请注意,虽然之前我使用过类似的代码,但我是从内存中编写的,并未在此示例中对其进行测试。您可能会遇到一些错误,因此可能需要进行一些调整。但它应该给你一般的想法。