Angular - debounceTime() and distinctUntilChanged() seems to have an issue

Viewed 887

I've got this validator, and the the problem is that even I have the debounceTime, after 500ms it runs ALL the keystrokes.

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

    });
}

So I add a timeout to fix the error

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)

    });
}

but I think there is a better solution with rxjs.

Any suggestions? this is how I call the validator

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