简体   繁体   中英

How to use RxJS “throttle” operator in Angular 2

Below is my component code where I am trying to use RxJS "throttle" operator.

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....'));
    }
}

The intention of this simple sample is to print "clicked...." only when there is a min gap of 1 sec between clicks.

But when I compile this code , it display below error and it points to ".throttle(1000)" line.

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

What is the mistake I am doing.

As others have suggested throttle() takes as an argument an Observable not the duration. However, what you describe suits more for a debounceTime() operator.

One thing worth mentioning is that since you're using Angular2 you're always using RxJS 5 and not the old RxJS 4. I guess you've found throttle here https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/throttle.md or http://reactivex.io/documentation/operators/debounce.html but these both describe RxJS 4.

The correct doc for RxJS 5 is http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-throttle and as you can see there're throttle() and throttleTime() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM