如何以角度2去抖动观察者函数?

时间:2016-09-25 22:27:04

标签: javascript angular typescript rxjs observable

我试图在角度2中收听onScroll事件,并且我创建了以下可用的代码,但是每个滚动事件都在调用下一个并且它会影响浏览器的性能。我希望observer.next函数非常轻量级,并且在订阅者处进行deboun就足够了,但要么它不是非常轻量级,要么我做错了。有人可以帮助我有效地去抖吗?

import {Component, Renderer, OnInit} from "@angular/core";
import {Subject, Observable, Observer} from "rxjs";
@Component({
selector: 'heading',
templateUrl: './heading.component.html',
styles: [require('./heading.component.scss')]
})

export class HeadingComponent implements OnInit {

observable: Observable<Event>;

constructor(private renderer: Renderer) {
    this.observable = new Observable<Event>(
        (observer: Observer<Event>) => {
            this.renderer.listenGlobal('window', 'scroll', (evt: Event) => {
                observer.next(evt);
        })
        }
    );
}

ngOnInit(): void {
    this.observable
        .debounceTime(400)
        .subscribe(
            (evt: Event) => console.log('next event' + evt),
            (err: string) => console.error(err),
            () => console.info('done')
        )
    }
}

2 个答案:

答案 0 :(得分:1)

在您的代码中.debounceTime(400)将其替换为.debounce(400)

请参阅文档:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/debounce.md

答案 1 :(得分:1)

我发现这样做的正确方法实际上如下(感谢Dzmitry&amp; Ryan来自角度gitter)

constructor() {
    this.observable = Observable.fromEvent(window, 'scroll')
        .debounceTime(400)
        .map(() => window.scrollY)
}