2

Getting Error "Clicked NaN times". What is the correct way to execute Rxjs code below?

import { Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/throttleTime';
export class AppComponent {
    count: number;
    title = 'app';
    @ViewChild('input') button: ElementRef;
    // @ViewChild('input1') button: ElementRef;
    constructor() {
    }

    ngAfterViewInit() {
        Observable.fromEvent(this.button.nativeElement, 'click')
            .throttleTime(1000)
            .scan(count => this.count + 1, 0)
            .subscribe(count => console.log(`Clicked ${count} times`));

    }
}
CozyAzure
  • 8,280
  • 7
  • 34
  • 52
  • why do you use `this.count` instead of `.scan(count => count + 1)`? – Max Koretskyi Jul 05 '17 at 09:56
  • so did [my answer](https://stackoverflow.com/a/44922980/2545680) help? – Max Koretskyi Jul 06 '17 at 11:12
  • yes thanks. Can you help in these (1) questions:https://stackoverflow.com/questions/44942742/using-rxjs-like-forkjoinhandling-multiple-observables-to-carry-multiple-reques?noredirect=1#comment76861810_44942742 (2)https://stackoverflow.com/questions/44826689/how-to-call-single-ajax-request-by-multiple-components-parallely-in-angular2-cli/44829500?noredirect=1#comment76795427_44829500 (3)https://stackoverflow.com/questions/44898818/using-rxjs-single-ajax-request-carrying-two-metadata-request-and-providing-resp?noredirect=1#comment76776111_44898818 –  Jul 06 '17 at 11:26
  • you can then mark my answer as accepted, I'll take a look at those other questions – Max Koretskyi Jul 06 '17 at 12:33

2 Answers2

2

You have to initiate your count field value in your class:

export class AppComponent {
     count:number = 0;
     // ...
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
2

You don't need to use this.count:

Observable.fromEvent(this.button.nativeElement, 'click')
   .throttleTime(1000)
   .scan(count => count + 1, 0)
   .subscribe(count => console.log(`Clicked ${count} times`));

You're passing an initial value here:

   .scan(count => count + 1, 0)
                            ^^^

As the docs say:

You can optionally pass scan a seed value as an additional parameter. scan will pass this seed value to the accumulator function the first time it is called (for the first emission from the source Observable) in place of the result from the missing prior call to the accumulator.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • Its giving Error at count+1 using .scan(count => count + 1, 0) –  Jul 05 '17 at 10:50
  • @ManzerAhmad Try `.scan((count: number) => count + 1, 0)` https://plnkr.co/edit/xqKWF2x6GLju8nOnADeg?p=preview – yurzui Jul 05 '17 at 11:45