pro*_*ogx 10 javascript rxjs typescript angular
我正在使用父组件和子组件。子组件具有输入字段,并将用户输入的值发送给父组件,如下所示:
<parent-component (sendInputValue)="getInputValue($event)"><parent-component>
Run Code Online (Sandbox Code Playgroud)
现在在父组件中我有这个:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说发生了这种情况:
那么,如果输入数据是 3 个字符,并且如果用户输入更多字符,则如何始终执行 API 调用,并且如果他删除字符并返回前 3 个字符,则不会发生任何事情,因为 API 已经发生了?非常感谢!
我认为你需要distinctUntilChanged 并且你可以在管道中使用过滤器
this.myService.getDataFromService(data)
.pipe(
filter(_ => data.length === 3),
distinctUntilChanged()
).subscribe(rs => console.log(rs));
Run Code Online (Sandbox Code Playgroud)
下面是您代码中的小调整,它将满足您告诉的要求。
您绝对可以使用 debounce、distinctUntilChanged、switchMap 运算符来改进此过程。
previousData = '' // create a property which will track of previous data from parent component.
getInputField(data){
if(data && data.length === 3 && data.length > previousData.length){
this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));
}
this.previousData = data || ''; // update previous data to current data after backend call.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1852 次 |
| 最近记录: |