gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:48:29 25 4
gpt4 key购买 nike

我有这段代码:

应用程序组件.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();
}
}

应用程序组件.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 - RxJS 在使用 filter() 时延迟更新下一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46550519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com