在https://www.learnrxjs.io/recipes/smartcounter.html,我找到了 Angular 2+ 中数字计数器的一个很好的示例,代码如下所示:
@Component({
selector: 'number-tracker',
template: `
<h3> {{ currentNumber }}</h3>
`
})
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();
}
}
现在这很好用,但我想传递一个变量 currentNumber 而不是 this.currentNumber 默认 0。
到目前为止,我已经走了这么远:
public currentNumber: number;
...
@Input()
set fanCountPrev(startRange: number) {
this.currentNumber = startRange
console.log('startRange: ', this.currentNumber)
}
...
但是当一个新值到达时,this.currentNumber 没有设置为以前的版本。
您有任何提示或示例来完成此操作吗?