我想在角度4中延迟按键事件。只想等待500ms来启动按键事件。试着按照angular.io tutorial中的示例进行操作 似乎没有从observable调用updateText()。看起来像是可观察的问题。
@Component({
selector: 'my-app',
template: `
<div>
<h2>Key event Demo {{name}}</h2>
</div>
<div>
<h4> KeyUp Event: </h4>
<input #keyUpInput (keyup)="onKeyUp(keyUpInput.value)">
<div>
<h5> KeyUp Text: </h5>
<p>{{values}}</p>
</div>
</div>
<div>
<h4> KeyUp Event With Delay: </h4>
<input #keyUpInputDelay (keyup)="onKeyUpDelay(keyUpInputDelay.value)">
<div>
<h5> KeyUp Text: </h5>
valuesDelay: <p>{{valuesDelay}}</p>
valuesDelayText: <p>{{valuesDelayText}}</p>
</div>
</div>
`,
})
export class App implements OnInit {
public name:string;
public values:string = '';
public valuesDelay:string = '';
public valuesDelayText:string = '';
private typeTerm = new Subject<string>();
constructor() {
this.name = `Angular! v${VERSION.full}`
}
ngOnInit(): void {
this.typeTerm.debounceTime(300).distinctUntilChanged().map(term => this.updateText(term));
}
public onKeyUp(value: string): void {
this.values += value + ' | ';
}
public onKeyUpDelay(value: string): void {
this.valuesDelay += value + ' | ';
this.typeTerm.next(value);
}
public updateText(value: string): void {
this.valuesDelayText += value + ' | ';
}
}
答案 0 :(得分:1)
<强>解决:强>
只需要订阅可观察的
ngOnInit(): void {
this.typeTerm.debounceTime(5000).distinctUntilChanged().subscribe(term => this.updateText(term));
}