【问题标题】:Looking for RxJs Operator that returns early, skipping operators below, not filter() or skip()寻找提前返回的 RxJs 运算符,跳过下面的运算符,而不是 filter() 或 skip()
【发布时间】:2019-09-14 09:23:13
【问题描述】:
  • 我有一个自动完成输入。
  • 每次输入或删除字母时,我都会发出一个 HTTP 请求。
  • 响应会映射到建议列表,我会在输入下方的下拉列表中显示该列表。

但是:如果最后一个字母被删除,使输入为空,我想跳过 HTTP 请求等并返回一个空数组。

所以我需要在管道中调用 first 的运算符,每次满足条件时都会跳过下面的所有运算符并“提前返回”,就像 for 循环中的“break”或“return”语句一样。

我不能使用 filter(),因为这个操作符会阻止结果 observable 发出。但我需要它发出来清除下拉列表。

<input [formControl]="formGroup.searchTerm">
<ul>
 <li *ngFor="let suggestion of suggestions$ | async">{{suggestion}}</li>
</ul>
suggetions$ = this.formGroup.valueChanges.pipe(
    pluck('searchString')
    // filter(searchString => searchString.length > 0) // does not help
    unknownOperator(searchString => {
        if(searchString.length === 0) {
            skipOperatorsBelowAndReturnThisInstead([])
        } else {
            continueWithOperatorsBelow(searchTerm)
        }
    })
    switchMap(values => this.http.get(this.url + values.term)),
    map(this.buildSuggestions),
),

谢谢!

【问题讨论】:

  • 只使用去抖动

标签: javascript rxjs rxjs-pipeable-operators


【解决方案1】:

您不能使用运算符跳过以下所有运算符。您必须根据条件切换到不同的流。

suggetions$ = this.formGroup.valueChanges.pipe(
  pluck('searchString'),
  switchMap(searchString => searchString.length === 0
    ? of([])
    : this.http.get(this.url + searchString).pipe(
      map(this.buildSuggestions)
    )
  )
);

【讨论】:

猜你喜欢
  • 2019-01-27
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
相关资源
最近更新 更多