typescript 如何在 Angular2/4/5 中实现自定义异步验证器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35521583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:17:50  来源:igfitidea点击:

How to implement Custom Async Validator in Angular2/4/5

typescriptangular

提问by Ankit Singh

1.Is it even supported by Angular yet ? see thisopen issue

1.Angular 还支持吗?看到这个未解决的问题

2.If it is, then what is wrong in the code below

2.如果是,那么下面的代码有什么问题

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.

它甚至不发出服务器请求。

回答by Thierry Templier

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)]
    });

Otherwise you won't be able to use the http property to execute your request.

否则您将无法使用 http 属性来执行您的请求。

This article could also give you some hints about asynchronous form validation (see the section "asynchronous validation"):

本文还可以为您提供有关异步表单验证的一些提示(请参阅“异步验证”部分):

回答by AJT82

as of newer versions of Angular, but pre version 5.0.0you would add the async validator as the third argument for your formcontrol:

从较新版本的 Angular 开始,但在预版本中,5.0.0您将添加异步验证器作为表单控件的第三个参数:

myControl: ['', [Validators.required], [this.asyncValidator.bind(this)]]

since version 5.0.0you can now mark the validators like so:

从版本开始,5.0.0您现在可以像这样标记验证器:

myControl: ['', {validators: [Validators.required], 
                 asyncValidators:[this.asyncValidator.bind(this)]}]

回答by Richard Frimpong

Hello guys thanks for the solution. However it didnt work for me outta the box.

大家好,感谢您的解决方案。然而,它对我来说开箱即用。

the problem was the async validator had to be a next parameter as part of the validators. so what worked for me was

问题是异步验证器必须是作为验证器一部分的下一个参数。所以对我有用的是

this.myForm = formBuilder.group({
        ImageId: ["",    
           [Validators.required], 
           [this.asynValidator.bind(this)]]
});

and tadaa!! the headache was gone. hope it helps someone.

和 tadaa !头痛消失了。希望它可以帮助某人。