var*_*run 31 javascript rxjs typescript rxjs5 angular
我正在尝试调用输入加密事件的服务.
HTML
<input placeholder="enter name" (keyup)='onKeyUp($event)'>
Run Code Online (Sandbox Code Playgroud)
以下是onKeyUp()功能
onKeyUp(event) {
let observable = Observable.fromEvent(event.target, 'keyup')
.map(value => event.target.value)
.debounceTime(1000)
.distinctUntilChanged()
.flatMap((search) => {
// call the service
});
observable.subscribe((data) => {
// data
});
}
Run Code Online (Sandbox Code Playgroud)
从浏览器的网络选项卡中可以看出,它正在调用每个按键事件的键盘功能(正如它应该做的那样),但我想要实现的是每个之间1秒的去抖时间.服务电话.此外,如果我移动箭头键移动,则会触发事件.
mar*_*tin 57
所以这个链是非常正确的,但问题是你正在创建一个Observable并在每个keyup事件上订阅它.这就是它多次打印相同值的原因.只有多个订阅,这不是你想要做的.
显然有更多方法可以正确地做到这一点,例如:
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" (keyup)='keyUp.next($event)'>
</div>
`,
})
export class App implements OnDestroy {
public keyUp = new Subject<KeyboardEvent>();
private subscription: Subscription;
constructor() {
this.subscription = this.keyUp.pipe(
map(event => event.target.value),
debounceTime(1000),
distinctUntilChanged(),
mergeMap(search => of(search).pipe(
delay(500),
)),
).subscribe(console.log);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
查看更新的演示:http://plnkr.co/edit/mAMlgycTcvrYf7509DOP
2019年1月:更新了RxJS 6
@marlin提供了一个很好的解决方案,它在angular 2.x中可以正常工作,但是在angular 6中,他们开始使用rxjs 6.0版本,并且语法略有不同,因此这里是更新的解决方案。
import {Component} from '@angular/core';
import {Observable, of, Subject} from 'rxjs';
import {debounceTime, delay, distinctUntilChanged, flatMap, map, tap} from 'rxjs/operators';
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" (keyup)='keyUp.next($event)'>
</div>
`,
})
export class AppComponent {
name: string;
public keyUp = new Subject<string>();
constructor() {
const subscription = this.keyUp.pipe(
map(event => event.target.value),
debounceTime(1000),
distinctUntilChanged(),
flatMap(search => of(search).pipe(delay(500)))
).subscribe(console.log);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28803 次 |
| 最近记录: |