重写可观察序列以使其更有意义

Rewriting observable sequence to make more sense

我正在创建一个 typeahead,它会在每次有人输入时远程调用 api,输入后会有一小段延迟。

此代码来自 bootstrap 4 typeahead example docs (Wikipedia example)。所有 .call_do 函数对我来说毫无意义。

Angular 组件

import { map } from 'rxjs/operator/map';
import { debounceTime } from 'rxjs/operator/debounceTime';
import { distinctUntilChanged } from 'rxjs/operator/distinctUntilChanged';
import { _catch } from 'rxjs/operator/catch';
import { _do } from 'rxjs/operator/do';
import { switchMap } from 'rxjs/operator/switchMap';

search = (text$: Observable<string>) =>
  _do.call(
     switchMap.call(
        _do.call(distinctUntilChanged.call(
           debounceTime.call(text$, 300)),
           () => this.searching = true),
           (term) => _catch.call(
              _do.call(this._service.search(term),
              () => this.searchFailed = false),
              () => {
              this.searchFailed = true;
              return of.call([]);
        })),
     () => this.searching = false);

HTML

      <md-input-container>
        <input mdInput [ngbTypeahead]="search"
           [(ngModel)]="model"
           [formControl]="lookupSubscriberControl"
           type="text"
           placeholder="Search by Name">
        <button type="submit" mdSuffix class="material-icons">search</button>
     </md-input-container>

1) 这个用英语怎么说?现在我不明白如何以正常的方式阅读它,因此无法根据我的需要重写它。

2) 有人可以帮我用更易读的格式重写吗?例如使用承诺的链式序列,或任何其他更有意义的东西。

我同意这似乎有点折磨人。我认为这是完成的,因为他们直接导入 operators 而不是使用 add/ 变体将运算符添加到 Observable 原型中。

基本上,如果我们按照传统方式重写它,Observables 它将看起来像这样:

search = (text$: Observable<string>) =>
  text$.debounceTime(300)
   .distinctUntilChanged()
   .do(() => this.searching = true)
   .switchMap(term => 
     this._service.search(term)
       .do(() => this.searchFailed = false)
       .catch(() => {
         this.searchFailed = true;
         return Observable.of([]);
       })
   )
   .do(() => this.searching = false);

请注意,您还需要更改运算符的导入,以便将它们添加到 Observable 原型中:

import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/switchMap';

从根本上说,它所做的只是接收一个正在去抖动的搜索查询 Observable,这样就不会使用陈旧数据发出请求,然后它会删除重复的连续查询。然后它使用 do 块来应用一些副作用,这些副作用可能会反映在 UI 中。最后,它对每个处理搜索请求和 returns 结果数组的查询发出请求。如果出现问题,它会在返回空数据数组之前捕获失败并设置错误状态。