我有一个观测变量,我打算在收到另一个观测变量的结果后动态更新。我的代码如下
import { of } from 'rxjs';
let total = of(0);
observer.subscribe(x => {
const add = (n) => + 1;
total.pipe(scan(add, 4)) //
total = total.pipe(scan(add, 4)); // works but doesn't update or change total on subsequent changes.
});
我对rxJS是个新手,希望得到任何帮助。
看起来像 BehaviorSubject
可以解决你的情况。
let total$ = new BehaviorSubject(0);
observer.subscribe(x => {
// ...
total$.next(valueYouWantItToEmit);
});
这演示了如何动态地累积一个和。
Component
import { Component } from "@angular/core";
import { of, Observable, Subject } from "rxjs";
import { scan, tap } from "rxjs/operators";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
amount = new Subject<number>();
amount$ = this.amount.asObservable();
total$ = this.amount$.pipe(
scan((acc, amt) => acc + amt),
tap(console.log)
);
doClick() {
this.amount.next(4);
}
}
超文本标记语言
<button (click)="doClick()">Add 4</button>
<p>Result: {{ total$ | async }}</p>
或者像之前建议的那样,你可以使用BehaviorSubject并从0开始。
你可以在这里找到这段代码的工作版本。
https:/stackblitz.comeditangular-adder-deborahk。
同时注意,你不应该尝试使用这样的语法来修改一个流。
myStream = myStream.pipe(...);