为什么Rsjx switchmap无法返回计时器(0,20)?

时间:2017-09-16 18:20:07

标签: angular rxjs

我有一个Ionic / Angular应用程序,我想实现一个计数器功能。 我发现了一个:https://github.com/btroncone/learn-rxjs/blob/master/recipes/smartcounter.md 做得好。所有信用都给了btroncone!

我开始将其作为一个组件来实现,但面对一个我不明白的错误。

这是到目前为止的代码:

    import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/timer';

@Component({
  selector: 'number-tracker',
  template: `<h3> {{ currentNumber }}</h3>`
})
export class CounterComponent implements OnDestroy {
//export class NumberTrackerComponent implements OnDestroy {
  @Input()
  set end(endRange: number) {
    this._counterSub$.next(endRange);
  }
  public currentNumber = 0;
  private _counterSub$ = new Subject();
  private _subscription : Subscription;

  constructor() {
    this._subscription = this._counterSub$
      .switchMap(endRange => {
        return timer(0, 20)
            .mapTo(this.positiveOrNegative(endRange, this.currentNumber))
            .startWith(this.currentNumber)
            .scan((acc, curr) => acc + curr)
            // .delayWhen(i => {
            //   easing here
            // })
            .takeWhile(this.takeUntilFunc(endRange, this.currentNumber));
      })
      .subscribe(val => this.currentNumber = val);
  }

  private positiveOrNegative(endRange, currentNumber) {
    return endRange > currentNumber ? 1 : -1;
  }

  private takeUntilFunc(endRange, currentNumber) {
    return endRange > currentNumber
      ? val => val <= endRange
      : val => val >= endRange;
  }

  ngOnDestroy() {
    this._subscription.unsubscribe();
  }
}

我得到的错误是:

enter image description here

我找到了一个例子,但这会返回一个可观察的:

clicks.switchMap(click => {
    return Rx.Observable.interval(500)
})

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

最后很简单,我不得不补充道:

import { timer } from 'rxjs/observable/timer'

https://github.com/btroncone

的所有学分