3

我有这个验证器,问题是即使我有 debounceTime,在 500 毫秒后它会运行所有击键。

slugTaken(model) {
    return control => new Promise((resolve, reject) => {
        let id = control.parent.controls._id.value;
        return control.valueChanges.debounceTime(500).distinctUntilChanged().subscribe(() => {
            this.httpClient.post('/api/slug', {id: id, slug: control.value, model: model, _loading: 1}).subscribe((res: any) => {
                    if (res.data > 0)
                        resolve({'duplicated': true});
                    else
                        resolve(null);
                })
            });

    });
}

所以我添加了一个超时来修复错误

slugTaken(model) {
    return control => new Promise((resolve, reject) => {
        let id = control.parent.controls._id.value;
        let $this = this;
        return control.valueChanges.debounceTime(500).distinctUntilChanged().subscribe(() => {
            clearTimeout(this.timeout);
            this.timeout = setTimeout(function(){
                $this.httpClient.post('/api/slug', {id: id, slug: control.value, model: model, _loading: 1}).subscribe((res: any) => {
                        if (res.data > 0)
                            resolve({'duplicated': true});
                        else
                            resolve(null);
                    })
                });
            }, 500)

    });
}

但我认为 rxjs 有更好的解决方案。

有什么建议么?这就是我调用验证器的方式

this.form = this.fb.group({
        _id: [],
        name: [null, Validators.required],
        slug: [null, [Validators.required], [this.validatorsService.slugTaken('transporters')]],
        transport_type_id: [],
        forthcrs_code: [],
        logoname: []
    });
4

0 回答 0