angular2:如何使用可观察对象去抖动窗口:调整大小 [英] angular2: How to use observables to debounce window:resize
问题描述
所以我试图找出一种消除窗口的方法:使用可观察对象来调整事件的大小,因此只有在用户停止调整窗口大小或经过一段时间而不更改大小(例如1秒)后,才会调用某种函数.
so i am trying to figure out a way to debouce window:resize events using observables, so some kind of function would be called only after user stoped resizing window or some time has passed without size change (say 1sec).
https://plnkr.co/edit/cGA97v08rpc7lAgitCOd
import {Component} from '@angular/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div (window:resize)="doSmth($event)">
<h2>Resize window to get number: {{size}}</h2>
</div>
`,
directives: []
})
export class App {
size: number;
constructor() {
}
doSmth(e: Event) {
this.size = e.target.innerWidth;
}
}
只是一个使用window:resize并显示其立即反应的简单示例(使用在单独的窗口中启动预览").
is just a simple sample that uses window:resize and shows that it reacts instantly (use "Launch preview in separate window").
推荐答案
我认为您不能使用可观察的方式对这种方式进行反跳.实际上,目前尚不支持此类操作,但是存在一个未解决的问题:
I think that you can't debounce this way using observable. In fact, such things aren't supported out of the box right now but there is an open issue for this:
要实现您的目标,可以直接使用Observable.fromEvent
来获取此事件的可观察值.因此,您可以在此可观察对象上应用debounceTime
运算符.
To achieve your goal, you could use directly the Observable.fromEvent
to get an observable for this event. So you can apply the debounceTime
operator on this observable.
以下是示例:
@Component({
(...)
})
export class App {
size: number;
constructor() {
Observable.fromEvent(window, 'resize')
.debounceTime(1500)
.subscribe((event) => {
this.doSmth(event);
});
}
doSmth(e: Event) {
console.log('do smth');
this.size = e.target.innerWidth;
}
}
请参阅此插件: https://plnkr.co/edit/uVrRXtnZj8warQ3qUTdN?p=preview
这篇关于angular2:如何使用可观察对象去抖动窗口:调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!