首页 > 解决方案 > 在字段中输入 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));
  }
}

现在假设发生这种情况:

  1. 用户输入: abc // API 调用得到执行,这很好
  2. 现在,用户输入: abcd // 没有执行 API 调用,这很好
  3. 现在用户删除了字母“d”,数据的新值将是“abc”我不想再次执行 API 调用,因为我们已经为“abc”执行了 API 调用
  4. 现在,如果用户删除字母“c”,数据的新值现在是“ab”。此时,不需要 API 调用
  5. 现在,如果用户添加字母“c”,新值将是“abc”。此时,API 调用是预期的。(这是工作)

那么,如果输入数据是 3 个字符,并且如果用户输入更多字符什么都不应该发生,并且如果他删除字符并返回前 3 个字符,那么应该如何始终执行 API 调用,因为 API 已经发生了?提前非常感谢!

标签: javascriptangulartypescriptrxjs

解决方案


我认为您需要distinctUntilChanged 并且您可以在管道中使用过滤器

this.myService.getDataFromService(data)
  .pipe(
    filter(_ => data.length === 3), 
    distinctUntilChanged()
  ).subscribe(rs => console.log(rs));

推荐阅读