- 我有一个自动完成输入。
- 每次输入或删除字母时,我都会发出 HTTP 请求。
- 响应被映射到建议列表,我将其显示在输入下方的下拉列表中。
但是:如果最后一个字母被删除,使输入为空,我想跳过 HTTP 请求等,而是返回一个空数组。
所以我需要一个在管道中调用 first 的运算符,每次满足条件时都会跳过下面的所有运算符并“提前返回”,就像 for 循环中的“break”或“return”语句一样。
我不能使用 filter(),因为这个运算符会阻止生成的可观察对象发出。但我需要它发出来清除下拉列表。
<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),
),
谢谢!
最佳答案
您不能使用运算符跳过下面的所有运算符。您必须根据情况切换到不同的流。
suggetions$ = this.formGroup.valueChanges.pipe(
pluck('searchString'),
switchMap(searchString => searchString.length === 0
? of([])
: this.http.get(this.url + searchString).pipe(
map(this.buildSuggestions)
)
)
);
关于javascript - 寻找提前返回的 RxJs 运算符,跳过下面的运算符,而不是 filter() 或 skip(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57934134/