主题重复操作上的Angular 7 rxjs / operator / debounceTime

问题描述 投票:0回答:2

在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();
}

以及带有四个keyup的浏览器控制台的图像:

enter image description here

为什么服务被叫两次?谢谢。

每次按下后我都会显示输入内容的图像。脉冲8并等待超过500毫秒。脉冲4567 ...你可以看到结果。

enter image description here

angular rxjs6
2个回答
0
投票

去抖时间仅保留时间间隔内的最后一个发射值。请在这里查看大理石图。 http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-debounceTime


0
投票

我也遇到了同样的情况,希望它可以帮助你/某人。 DEMO

我有点困难时间绕着可观察的观察者。他有点关于它是如何发生的,并且链接是关于更深入的内容的文章。

我们使用RxJS主题,它既是Observable又是Observer。我们的主题有一个next()方法,我们将在模板中使用它来在我们输入时将搜索词传递给主题。 real-time-search-angular-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>
© www.soinside.com 2019 - 2024. All rights reserved.