如何实现异步验证在2角 [英] How to implement Async Validator in Angular 2
本文介绍了如何实现异步验证在2角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
1 难道甚至角支撑了吗?看到这个的悬而未决的问题。
1. Is it even supported by Angular yet ? see this open issue
2 如果是,那么什么是错在下面
2. If it is, then what is wrong in the code below
export class someClass{
myForm:ControlGroup;
constructor(public http:Http, public formBuilder:FormBuilder)
this.myForm = formBuilder.group({
ImageId: ["", Validators.required, this.asynValidator]
});
asyncValidator(control: Control): {[key: string]: any} {
return new Promise (resolve => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.get('http://localhost/ImageIdValidate?id='+ control.value, {headers:headers})
.map(res => res.json())
.subscribe(data => {
console.log(data);
if(data != null) {
resolve({"duplicate": true})
}
else resolve(null);
})
});
});
}
}
它甚至没有一台服务器的请求。
It doesn't even make a server request.
推荐答案
您需要在您的方法绑定组件实例本身的描述如下:
You need to bind your method on the component instance itself as described below:
this.myForm = formBuilder.group({
ImageId: ["",
Validators.required,
this.asynValidator.bind(this)]
});
否则,你将无法使用http属性来执行您的要求。
Otherwise you won't be able to use the http property to execute your request.
本文还可以给你有关异步表单验证一些提示(参见异步验证):
This article could also give you some hints about asynchronous form validation (see the section "asynchronous validation"):
这篇关于如何实现异步验证在2角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文