javascript - 在字段中输入 3 个字符后如何执行 API 调用?
问题描述
我正在使用父子组件。子组件具有输入字段,并将用户输入的值发送给父组件,如下所示:
<parent-component (sendInputValue)="getInputValue($event)"><parent-component>
现在在父组件中我有这个:
getInputField(data){
console.log(data); // this prints the data (Example: abc)
// then here I'm just executing the API call ONLY if data length is 3
if(data.length === 3){
this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));
}
}
现在假设发生这种情况:
- 用户输入: abc // API 调用得到执行,这很好
- 现在,用户输入: abcd // 没有执行 API 调用,这很好
- 现在用户删除了字母“d”,数据的新值将是“abc”我不想再次执行 API 调用,因为我们已经为“abc”执行了 API 调用
- 现在,如果用户删除字母“c”,数据的新值现在是“ab”。此时,不需要 API 调用
- 现在,如果用户添加字母“c”,新值将是“abc”。此时,API 调用是预期的。(这是工作)
那么,如果输入数据是 3 个字符,并且如果用户输入更多字符什么都不应该发生,并且如果他删除字符并返回前 3 个字符,那么应该如何始终执行 API 调用,因为 API 已经发生了?提前非常感谢!
解决方案
我认为您需要distinctUntilChanged 并且您可以在管道中使用过滤器
this.myService.getDataFromService(data)
.pipe(
filter(_ => data.length === 3),
distinctUntilChanged()
).subscribe(rs => console.log(rs));
推荐阅读
- rust - 迭代元组数组时,错误“no field `n`”是什么意思?
- java - 什么调用 Android View.OnClickListener API 方法?
- math - DeepLearning4J的具体数学实现
- bash - sed 不会从文件中删除多行字符串的实例
- sql-server - 在条件似乎不起作用的 T-SQL 中使用替换
- java - 阻塞相当于 Java 的 Timer
- html - 在里面并排显示两个div元素
- php - PHP mysql插入不工作没有错误检查
- javascript - koa:promise vs async await 中间件
- reactjs - 在反应中导出 const