Custom async check does not work when returning a promise

I call the web api to check if urlalias is available, for this task I use httpservice in my asynchronous validator. The problem is that when the validator is called, the entire correct code path is executed (all console.log()work and behave as expected).

If the promise from validation is returned / resolved to zero or { 'isUrlAliasActivityMainAvailable': true }, the controller always displays the error object as follows, thereby saving the form state as invalid, why (hell!)?

I use: angular: 2.1.0 and rxjs: 5.0.0-beta.12

enter image description here

This is my shaper:

this.formBuilder.group({
//...
"urlAliasActivityMain":[null,[ ValidatorsZr.isUrlAliasActivityMainAvailableAsyncValidator(this.httpActivityService)]],
});

This is my validator:

   public static isUrlAliasActivityMainAvailableAsyncValidator(httpActivityService: HttpActivityService) {
        return function (control: FormControl): Promise<any> | Observable<any> {

            const promise = new Promise<any>(
                (resolve, reject) => {
                    httpActivityService.isUrlAliasActivityMainAvailable(control.value)
                        .subscribe(
                        (data: any) => {
                            console.log("isUrlAliasActivityMainAvailableAsyncValidator");
                            console.log(data);
                            if (data == false) {
                                console.log("data == false");
                                resolve({ 'isUrlAliasActivityMainAvailable': true });
                            }
                            else {
                                console.log("data == true");
                                resolve(null);
                            }
                        },

                    )
                });

            return promise;
        }
    }
+4
1

.

[objectValue, synchronous validators, asynchronous validators]

control (formState: Object, validator?: ValidatorFn | ValidatorFn [], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn []): FormControl FormControl formState, asyncValidator.

formState , , , .

, :

this.formBuilder.group({
//...
"urlAliasActivityMain":[null, null, ValidatorsZr.isUrlAliasActivityMainAvailableAsyncValidator(this.httpActivityService)],
});
+14

Source: https://habr.com/ru/post/1661668/


All Articles