【问题标题】:Angular async Validator debounce input角度异步验证器去抖动输入
【发布时间】:2019-03-16 00:44:49
【问题描述】:

我想为我的 Angular 表单组编写一个自定义异步验证器,该 jop 用于检查 url 是否可访问。但是,如果我对从 AbstractControl 更改的值进行去抖动,则 Control 总是以某种方式无效。 这是我目前的代码

export class UrlValidator {
static createValidator(http: HttpClient) {
    return (control: AbstractControl) => {
        const url = control.value;

        return http.get(url).pipe(
            throttleTime(1500),
            catchError(err => {
                console.log('err', err);
                if (err.status && err.status === 200) return of(null);
                return of({ input: 'urlError' });
            })
        );
    };
}
}

debouncetime 调用目前不执行任何操作

提前致谢

【问题讨论】:

  • 能否提供更多代码(尤其是您的表单?)
  • 乍一看,我可以建议将http请求和历史逻辑移动到单独的服务中,在组件/指令内部处理这个是不好的做法。

标签: angular forms validation rxjs observable


【解决方案1】:

您可能必须在验证器之外进行去抖动。如果输入源不断发射,验证器将被连续调用,在 http 调用后设置 debounce 不会做任何事情。

export class UrlValidator {
static controlValue=new Subject()
static createValidator(http: HttpClient) {
    UrlValiator.controlValue.next(control.value)
    return (control: AbstractControl) => {
        return controlValue.pipe(
            debounceTime(1500),
            switchMap(()=>http(url))
            catchError(err => {
                console.log('err', err);
                if (err.status && err.status === 200) return of(null);
                return of({ input: 'urlError' });
            })
        );
    };
}
}

【讨论】:

    【解决方案2】:

    好的,问题是,Observable 卡在了挂起状态。 在 http observable 中添加 .first() 就可以了

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 2019-03-23
      • 2016-08-23
      • 2020-02-22
      • 2023-03-12
      • 2014-08-22
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多