rxjs - 使用 filter() 运算符过滤值时触发副作用
问题描述
我正在处理在 debounceTime() 之后触发的用户名搜索输入。我还过滤掉了值。如果值被过滤(例如设置错误消息和停止加载程序),我想触发一些副作用。
我现在通过使用 tap() 并检查我稍后在 filter() 函数中检查的相同谓词来实现这一点。我觉得这很糟糕/有更合适的方法来实现这一点。
private setUserSearchObservable() {
this.userSearch = userSearch$.pipe(
tap(() => this.loading = true),
debounceTime(500),
this.filterValuesWithErrorMessages(),
......
);
}
private filterValuesWithErrorMessages() {
return pipe(
tap((val: string) => { if (this.usernamesMatch(val)) { this.errorMessage = 'You will be added to the frame automatically'; this.loading = false; }}),
tap((val: string) => { if (this.usernameInArray(val)) { this.errorMessage = 'User is already added'; this.loading = false; }}),
tap((val: string) => { if (val.length < 2) { this.errorMessage = ''; this.loading = false; }}),
filter((val: string) => (val.length >= 2 && !this.usernamesMatch(val) && !this.usernameInArray(val))),
);
}
如您所见,我在 filter() 上使用它们之前使用 tap() 明确检查完全相同的条件。是否有操作员/不同的模式可以让我以更简洁的方式实现这一目标?
解决方案
稍微重构了你的代码,没有特定的操作符来处理错误检查,你可以使用switchMap
内部 observable egof
来never
控制结果是否应该通过。
private setUserSearchObservable() {
this.userSearch = userSearch$.pipe(
tap(() => this.loading = true),
debounceTime(500),
map((value) => this.filterValuesWithErrorMessages(value)),
swtichMap(msg => {
if (msg !== false) {
this.errorMessage = result
this.loading = false
return never()
}
return of(true)
})
);
}
private filterValuesWithErrorMessages(val) {
if (this.usernamesMatch(val)) return 'You will be added to the frame automatically'
if (this.usernameInArray(val)) return 'User is already added'
if (val.length < 2) return ''
return false
}
推荐阅读
- bash - 这是什么意思?bash 和 nagios 编程
- javascript - 使用 Ant Design (antd) 的分页和卡片组件?
- java - Spring MVC AbstractView Java 配置
- php - 每当我单击表单上的提交按钮时,它会将我重定向到空白的 php 链接,这是为什么呢?
- visual-studio - Visual Studio 2015 始终以管理员身份打开
- java - 是否可以从 SourceForge 发布到 Maven 中央存储库?
- c# - 如何在二维数组和锯齿状数组之间转换?
- java - Java从JSON中提取数据不起作用
- c - C中的累积和正在爆炸到无穷大
- python - Python 3 Count 在函数内更新,但值不会在函数外更新