无法使debounceTime()或throttleTime()处理Angular http请求

MrC*_*oft 5 rxjs5 angular

对于我的生活,我无法做到这一点.我搜索过并搜索过,但是我找不到任何例子(所有的例子都有.fromEvent(),没有一个http.get).

在我的模板中,我有这样的输入:

<input type="text" (input)="categoriesSearch($event)">
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我有以下内容:

categoriesSearch(event) {
    this.categoriesSubscription = this.apiService
        .getCategoriesList(this.uploadForm.get('categories').value)
        .debounceTime(3000)
        // .throttleTime(3000)
        .subscribe(
            (response) => {
                this.categories = response.data;
            }
        );
}
Run Code Online (Sandbox Code Playgroud)

这是我的ApiService中的方法:

getCategoriesList(keyword = null) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Bearer', this.authService.user.token);

    const getParams: URLSearchParams = new URLSearchParams();
    getParams.set('keyword', keyword);
    return this.http.get(this.apiHost + '/categories', { headers: headers, search: getParams })
        .map(response => response.json());
}
Run Code Online (Sandbox Code Playgroud)

在该categoriesSearch()方法中,我都试过debounceTime()throttleTime()(我还进口了他们,当然import 'rxjs/add/operator/debounceTime',import 'rxjs/add/operator/throttleTime').

但http.get请求根本没有被去除或限制!如果我在3秒内输入10个字符,则会产生10个http请求.

this.http.get如果自上次请求后至少已经过了3秒或者"没有请求"(意味着最初的3秒延迟),我怎么告诉我只提出请求?好吧,也许在这里我应该说"因为我最后输入了一些内容".

我也尝试在.map()运营商之前直接在服务中使用debounceTime()/ throttleTime()- 但结果是一样的.

Cha*_*oot 11

但http.get请求根本没有被去除或限制!如果我在3秒内输入10个字符,则会产生10个http请求.

你以错误的方式实施.您首先需要捕获输入,应用deounce并执行HTTP请求.

你可以用几种方式实现

1)Observable.fromEvent

 <input type="text" #input>
Run Code Online (Sandbox Code Playgroud)

零件

 @ViewChild('input') text: ElementRef;

  ngAfterViewInit() {
    let text$ = Observable.fromEvent(this.text.nativeElement, 'keyup')
     .do(() => console.log("keyup"))
    .debounceTime(3000)
     .distinctUntilChanged()
    .switchMap(() => getCategoriesList())
        .subscribe(res => console.log(res));
  }
Run Code Online (Sandbox Code Playgroud)

2)使用主题

<input type="text" (keyup)="search($event)">
Run Code Online (Sandbox Code Playgroud)

零件

  searchTerms = new Subject<string>();

search(term: string): void {
    this.searchTerms.next(term);
  }

ngOnInit(): void {

    this.searchTerms
      .debounceTime(3000)
      .distinctUntilChanged()
      .switchMap(() => getCategoriesList())
      .subscribe(term => { 
       console.log();
     });
Run Code Online (Sandbox Code Playgroud)

3)使用表单控件

 <input type="text" [formControl]="term">
Run Code Online (Sandbox Code Playgroud)

零件

  term = new FormControl();

  ngOnInit() {
    this.items = this.term.valueChanges
                 .debounceTime(3000)
                 .distinctUntilChanged()
                 .switchMap(term => getCategoriesList(term))
                 .subscribe(res => console.log(res));
  }
Run Code Online (Sandbox Code Playgroud)