S
S
stepa902020-05-29 18:54:16
Angular
stepa90, 2020-05-29 18:54:16

How to avoid duplicate AsyncValidator requests?

I created a form validator using this article .

@Directive({
    selector: '[instrumentationNameValidator][ngModel],[instrumentationNameValidator][FormControl]',
    providers: [
        {provide: NG_ASYNC_VALIDATORS, useExisting: InstrumentationNameValidator, multi: true}
    ]
})
export class InstrumentationNameValidator implements AsyncValidator {
validatorResult: Observable<ValidationErrors>;
oldValue : string;
    constructor(private http: HttpClient,
                private config: AppConfiguration,
                private user: UserInfoService) {
    }

    validate(control: AbstractControl): Observable<ValidationErrors | null> {
        const params = new HttpParams().set('data', control.value);
       if(this.oldValue != control.value){
       this.oldValue = control.value
        this.validatorResult = this.http.get<boolean>('http:/mysite.com/check', {params})
            .pipe(
                map((isUsed) => {
                    // null no error, object for error
                    return !isUsed ? null : {
                        instrumentationNameValidator: 'Name exists already.'
                    };
                })
            );
       }
        
        return this.validatorResult;
    }
}

I have a 10 character limit. I added, for example from the article, a check if the value has changed or not so that if the user has already entered 10 characters and starts poking again, requests are not sent with the same values.
and everything works great as long as the response from the server has time to arrive before I press the button again. Those. if you hold down the button I see this picture 5ed11fc614880730232667.png
I added finalize(()=>console.log('finalize')) to the http request and I see that despite the fact that I do not explicitly call the http request, the validator does it somehow for me. I tried to add share and in this case there is only one request, but then if the value has changed and now I really need a new http request, the previous ones do not end and hang in pending until the server responds, but I don’t need it.
Since there are other handlers on the form that I didn't do, I can't solve it at the form level... I need to do something with the validator. I will be very glad to advice

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question