Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 检查新值时,角度异步校验器未取消订阅_Angular_Rxjs - Fatal编程技术网

Angular 检查新值时,角度异步校验器未取消订阅

Angular 检查新值时,角度异步校验器未取消订阅,angular,rxjs,Angular,Rxjs,我正在尝试制作一个验证器,用于检查电子邮件地址是否已经存在,并且像往常一样,我们不希望服务器在用户仍在输入字段中键入电子邮件地址时受到请求的影响 目前代码如下所示 return Observable.timer(1000).switchMap(() => { return this.userService.emailExists(control.value) .mapTo(exist => Observable.of({ "emailExists": e

我正在尝试制作一个验证器,用于检查电子邮件地址是否已经存在,并且像往常一样,我们不希望服务器在用户仍在输入字段中键入电子邮件地址时受到请求的影响

目前代码如下所示

return Observable.timer(1000).switchMap(() => {
       return this.userService.emailExists(control.value)
        .mapTo(exist => Observable.of({ "emailExists": exist }))
        .catch(err => Observable.of({ "emailExists": true }));
    }).subscribe();
通过阅读前面的Stackoverflow post(),当验证器一次又一次地运行时,它应该从前面的可观察对象中取消订阅(不将它们排队),但似乎没有这样做,因此通过上面的代码,我们在每次击键和执行1秒计时器时都会命中服务器

我的代码和post之间存在差异-没有.subscribe()任何东西都不起作用,而且从未进行过可观察的http调用-因此我只能假设Angular或Rxjs的更新导致了这种行为的改变


我们想要做的是,使用Observable而不是使用setTimeout和clearTimeout,使用Angular form async validator,当用户暂停/停止键入大约1秒时,只向服务器发出请求。非常感谢您的帮助。

您应该使用
debounceTime
操作符,而不是
Observable.timer

return this.userService.emailExists(control.value)
           .debounceTime(1000)
           .mapTo(exist => Observable.of({ "emailExists": exist }))
           .catch(err => Observable.of({ "emailExists": true }));

以下是
DebounceTime
的详细信息:

去BounceTime
延迟可观测源发出的值,但 如果源上出现新值,则先前的待定延迟排放 可见的


您应该使用
debounceTime
操作符,而不是
Observable.timer

return this.userService.emailExists(control.value)
           .debounceTime(1000)
           .mapTo(exist => Observable.of({ "emailExists": exist }))
           .catch(err => Observable.of({ "emailExists": true }));

以下是
DebounceTime
的详细信息:

去BounceTime
延迟可观测源发出的值,但 如果源上出现新值,则先前的待定延迟排放 可见的


对所有的人来说,在有角度的文档中很容易漏掉,就像我做的那样。异步验证器与同步验证器不包含在同一个参数中,它是一个单独的参数-(),在Angular文档中很容易丢失,就像我做的那样。异步验证器与同步验证器不包含在同一个参数中,它是一个单独的参数-()