异步验证器永远不会解析为真

Async Validator never resolves to true

我创建了以下验证函数:

passwordValid(control:Control):{ [key: string]: any; } {
    clearTimeout(this.timer);
    if (control.value){
        let q = new Promise((resolve) => {
            this.timer = setTimeout(()=>{
                this._http.post('/check', control.value)
                    .subscribe(
                        success=>{
                            resolve(null);
                        },
                        error=>{
                            resolve({'invalid': true});
                        })
            },1000);
        });
        return Observable.fromPromise(q);
    };
}

当我像这样将它挂接到控件时:

control: ['', this.passwordValid.bind(this)]

它从不将控件有效性更改为 'valid'。它总是无效的。我做错了什么?

使用您的代码,您将验证器注册为同步验证器(控件的第二个参数)。

异步的需要用到第三个参数:

control: ['', null, this.passwordValid.bind(this)]

这篇文章可能会让您感兴趣:

异步验证器应位于索引 2

control: ['', null, this.passwordValid.bind(this)]