angular - Angular 7 rxjs/operator/debounceTime 对主题重复操作
问题描述
在 Angular7 应用程序中,我使用以下 html 代码捕获了数字输入的 KeyUp 事件:
<input fxFlex
type="number"
formControlName="DM"
(keyup)="changeDM()">
</div>
我使用 debounceTime(500) 来延迟对处理表单的服务的调用。我写了一个 1, 2, 3, 4 ... 数字,我看到 debounceTime(500) 工作正常,但它对服务进行了重复调用。看代码:
subject: Subject<any> = new Subject();
.....
this.subj.pipe(debounceTime(500)).subscribe(() => {
console.log('==CALL TO SERVICE==');
this.service.setForm( this.form.valid, this.form.value );
});
changeDM(): void {
console.log('changeDM==============');
this.subject.next();
}
以及带有四个键的浏览器控制台的图像:
为什么服务被调用两次?谢谢你。
每次按下后我都会在其中显示输入内容的图像。脉冲 8 并等待超过 500 毫秒,脉冲 4567 ... 可以看到结果。
解决方案
我在同样的情况下也遇到了一些麻烦,希望它可以帮助你/某人。演示
我很难将头绕在可观察者和观察者身上。他有点关于它是如何发生的,并且链接是更深入的外卖文章。
我们使用了一个 RxJS 的 Subject,它既是 Observable 又是 Observer。我们的主题有一个 next() 方法,我们将在模板中使用该方法在我们键入时将搜索词传递给主题。 实时搜索角rxjs
export class Example {
response: any;
term$: Subject < string > = new Subject < string > ();
constructor(private exampleSerivce: ExampleService) {
this.exampleSerivce.search(this.term$).subscribe(res => this.response = res);
}
}
@Injectable()
export class ExampleService {
constructor(private http: HttpClient) {}
search(term: Observable < string > ) {
return term.pipe(
filter(val => !!val),
distinctUntilChanged(),
debounceTime(500),
switchMap(term => this.searchTodo(term)),
catchError(() => {
return of({
error: 'no todo found'
});
})
);
}
searchTodo(term: string) {
return this.http.get(`https://jsonplaceholder.typicode.com/todos/${term}`);
}
}
<div class="example-container">
<mat-form-field>
<input matInput placeholder="Input - Numbers only please" (keyup)="term$.next($event.target.value)">
</mat-form-field>
<div class="todo">
{{response | json}}
</div>
</div>
推荐阅读
- oracle - PL/SQL 可重用的动态 sql 程序,用于相同类型的任务但不同的表和列
- php - 开关盒无法正常工作
- javascript - 样式化 SSL 证书徽标
- mysql - 运行 mysql:“systemctl start mysqld.service”错误
- java - Java:为从文件存储到数组中的每个单词增加 wordCount
- javascript - 如何使用 Javascript 实时搜索/过滤解析的 JSON 数据?
- android-layout - 使用具有可滚动约束布局的相对布局来实现冻结窗格效果
- spring-boot - 将 Spring Boot 从 1.5.12 迁移到 1.5.13 后,ehcache 出现错误
- python - 找不到满足 ruamel 要求的版本(来自版本:)没有为 ruamel 找到匹配的发行版
- c# - 我应该旋转炮塔的哪个部分来面对目标?以什么速度?