首页 > 解决方案 > 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 ... 可以看到结果。

在此处输入图像描述

标签: angularrxjs6

解决方案


我在同样的情况下也遇到了一些麻烦,希望它可以帮助你/某人。演示

我很难将头绕在可观察者和观察者身上。他有点关于它是如何发生的,并且链接是更深入的外卖文章。

我们使用了一个 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>

推荐阅读