javascript - 使用filter()时RxJS延迟更新下一个值

标签 javascript angular rxjs

我有这段代码:

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 次,然后再次按添加按钮时,除非我多次按添加​​按钮,否则它不会更新。

这是为什么呢?我该如何解决这个问题?

示例:

The problem in GIF

最佳答案

在扫描中尝试这个。原因是每次发出一个值时,无论是否过滤,都会处理扫描。

.scan((x, y) => (x + y) >= 0 ? x + y : 0, 0)

关于javascript - 使用filter()时RxJS延迟更新下一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46550519/

相关文章:

javascript - RxJS 自定义运算符不调用完成

javascript - 如何在模板中使用异步命令显示数据?

javascript - 在 Javascript 中获取二维数组中特定元素的值

angular - 如何解析 Angular 4 中的应用程序级数据?

javascript - 尝试在 Django 中构建一个使用 chessboard.js 显示棋盘的网页

javascript - 单击外部后 ngx-color-picker 对话框关闭

angular - 使用 Angular 通过 HTTP 发送 SOAP 请求?

rxjs - 不退订的共享运营商

java - 从 HTML 执行 Webdriver 脚本

javascript - MapQuest Leaflet Api - 获取时间和距离的优化路径