【问题标题】:debounceTime send request each timedebounceTime 每次发送请求
【发布时间】:2020-11-16 19:55:49
【问题描述】:

在输入电子邮件表单时,异步验证器每次都会向 JSON 发送请求。它检查现有的电子邮件,以输入每个字母。如何调用服务器并检查一次,而不是每个字母?

isEmailExist(): AsyncValidatorFn  {
   return (control: AbstractControl): Observable<any> => {
     return this.usersService.getUserByEmail(control.value).pipe(
        debounceTime(2000),
        map(users => {
            if (users.some(user => user.email.toLowerCase() === control.value.toLowerCase())) {
               return { isExist: true };
            } else {
               return null;
            }
        })
     ) 
   }
  }

【问题讨论】:

  • 你的问题是什么?

标签: javascript angular typescript rxjs debounce


【解决方案1】:

debounceTime 运算符必须在发出 keyup 事件的 Observable 之后通过管道传输。 您可以使用fromEvent 运算符来实现。

【讨论】:

    【解决方案2】:

    梅雷,你可以用{updateOn:'blur'},见the docs

    另一个选项是不使用验证器并在提交中检查 isEmailExist

    另一种选择是您在 debounceTime 中“检查”电子邮件,但值会发生变化。 想象一下,你有一个变量“check”和一个控件

      check=false;
      control=new FormControl('',Validators.required,this.customValidator().bind(this))
    

    bind(this)make,你可以使用你的组件的一个变量,所以你的 customValidator 可以像

      customValidator(){
        return (control)=>{
        if (!this.check)  //if the variable in component is false return of(null)
          return of(null)
                          //else you call to the service
         return this.usersService.getUserByEmail(control.value).pipe(
           map(users => {
              if (users.some(user => user.email.toLowerCase() ===
                                       control.value.toLowerCase())) {
                  return { isExist: true };
              } else {
                 return null;
              }
         })
        }
      }
    

    现在,在定义 FormControl 之后订阅 valueChanges

    this.control.valueChanges.pipe(debounceTime(300)).subscribe(_=>{
      this.check=true;
      this.control.updateValueAndValidity({emitEvent:false});
      this.check=false;
    })
    

    this stackblitz我用傻瓜函数模拟了对你服务的调用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-24
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2020-10-28
      • 2023-04-07
      相关资源
      最近更新 更多