我有这段代码:
app.component.ts:
import {Component, AfterViewInit, ChangeDetectorRef} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/filter';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
changes$ = new Subject<number>();
current$ = this.changes$
.scan((x, y) => x + y, 0)
.filter((x) => x >= 0);
constructor(private cdRef: ChangeDetectorRef) {}
ngAfterViewInit(): void {
this.changes$.next(0);
this.cdRef.detectChanges();
}
}
app.component.html:
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<button (click)="changes$.next(-1)">-1</button>
<button (click)="changes$.next(1)">+1</button>
<div>
<span>{{ current$ | async }}</span>
</div>
<div>
<span>{{ current$ | async }}</span>
</div>
<div>
<span>{{ current$ | async }}</span>
</div>
</div>
我的问题是我不想低于 0,所以我添加了过滤运算符。这解决了我的问题,但是当我达到 0 并按减号按钮 10 次,然后再次按添加按钮时,除非我多次按添加按钮,否则它不会更新。
这是为什么呢?我该如何解决这个问题?
示例:
最佳答案
在扫描中尝试这个。原因是每次发出一个值时,无论是否过滤,都会处理扫描。
.scan((x, y) => (x + y) >= 0 ? x + y : 0, 0)
关于javascript - 使用filter()时RxJS延迟更新下一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46550519/