【问题标题】:AsyncValidator prevent http if value is null如果值为空,AsyncValidator 会阻止 http
【发布时间】:2018-07-11 19:28:19
【问题描述】:

我创建了一个AsyncValidator 来检查用户名的唯一性。

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

【问题讨论】:

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


    【解决方案1】:

    为什么不翻转需求? 更改代码,如

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

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 1970-01-01
      • 2021-10-28
      • 2017-11-18
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      相关资源
      最近更新 更多