动态更新可观察对象或类型编号

时间:2020-04-24 11:48:04

标签: rxjs

我有一个可观察变量,我打算在收到另一个可观察变量的结果后动态更新。我的代码如下所示

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的新手,将不胜感激。

2 个答案:

答案 0 :(得分:0)

看起来像top = detection.Top # with capital letters, just as they are shown by the print() statement. 可以解决您的情况。

BehaviorSubject

答案 1 :(得分:0)

这演示了如何动态求和:

组件

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);
  }
}

HTML

<button (click)="doClick()">Add 4</button>
<p>Result: {{ total$ | async }}</p>

或者如先前建议的那样,您可以使用BehaviorSubject并从0开始。

您可以在此处找到此代码的有效版本:

https://stackblitz.com/edit/angular-adder-deborahk

还请注意,您不应尝试使用如下语法修改流:

myStream = myStream.pipe(...);
相关问题