如何在Angular2/4/5中实现自定义异步验证器 [英] How to implement Custom Async Validator in Angular2/4/5

查看:143
本文介绍了如何在Angular2/4/5中实现自定义异步验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1..Angular甚至还支持吗?参见公开问题

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"):

这篇关于如何在Angular2/4/5中实现自定义异步验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆