如何在 Angular 2 中使用 RxJS "throttle" 运算符

How to use RxJS "throttle" operator in Angular 2

下面是我尝试使用 RxJS "throttle" 运算符的组件代码。

import { Component , OnInit , OnChanges , DoCheck  } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/throttle';

@Component({
    selector:'rx1',
    template: `
    <h2> Rx1 Component </h2>
    <button name="btn" valur="click"> 
})

export class Rx1Component implements OnInit {   

    ngOnInit() {
        var button = document.getElementsByTagName('button');

        Observable.fromEvent(button, 'click')
            .throttle(1000) 
            .subscribe(() => console.log('clicked....'));
    }
}

这个简单示例的目的是仅当点击之间的最小间隔为 1 秒时才打印 "clicked...."。

但是当我编译这段代码时,它显示在错误下方并指向“.throttle(1000)”行。

Argument of type 'number' is not assignable to parameter of type '(value: {}) => SubscribableOrPromise'.

我做错了什么。

正如其他人所建议的那样,throttle() 将 Observable 作为参数而不是持续时间。但是,您描述的内容更适合 debounceTime() 运算符。

值得一提的是,由于您使用的是 Angular2,因此您总是使用 RxJS 5 而不是旧的 RxJS 4。我猜您已经找到 throttle 这里 https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/throttle.md or http://reactivex.io/documentation/operators/debounce.html 但这些都描述了 RxJS 4.

RxJS 5 的正确文档是 http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-throttle,如您所见,有 throttle()throttleTime().