如果值为null,则AsyncValidator会阻止http

时间:2018-02-01 12:56:20

标签: angular typescript angular2-forms angular2-observables angular-validation

我创建了一个AsyncValidator来检查userName的唯一性。

根据this示例,我添加了500毫秒的延迟。

但是,如果输入值没有通过特定要求,我根本不知道如何防止服务(http)被调用。

import { Injectable } from "@angular/core";
import { AsyncValidator, AbstractControl } from "@angular/forms";
import { Observable } from "rxjs/Rx";
import { UsersService } from "../services/UsersService";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';

@Injectable()
export class UniqueUserNameAsyncValidator implements AsyncValidator {
    constructor(private usersService: UsersService) {

    }

    validate(c: AbstractControl): Promise<any> | Observable<any> {
        return Observable.timer(500).switchMap(() => {
            if(!c.value || c.value.length < 4) {
                // TODO
                // prevent call to service if the control value is null / empty

                // return null; // Doesn't work
            }

            return this.usersService.getByName(c.value)
                .map(p => {
                    return { uniqueUserName: true };
                });
        });
    }
}

1 个答案:

答案 0 :(得分:0)

为什么不翻转要求? 改变代码如

validate(c: AbstractControl): Promise<any> | Observable<any> {
    return Observable.timer(500).switchMap(() => {
        if(c.value || c.value.length >= 4) {
            return this.usersService.getByName(c.value)
            .map(p => {
                return { uniqueUserName: true };
            });
        }else{
          //do things you want if requirements are not fulfilled
        }

    });
}