我有一個服務,它有兩個 observablestoreValueOne$和storeValueTwo$,它們的型別number和更新頻率很高,但不是同時更新。
我想添加 的值 storeValueOne,storeValueTwo 并將它們存盤到另一個跟蹤更改的可觀察物件中。
使用ngrx merge,我可以將兩個可觀察值組合在一起,但我不清楚如何進行計算,因為它們以不同的速率更新,我也不知道哪一個改變了它的值。
import { Injectable } from '@angular/core';
import { forkJoin, map, merge } from 'rxjs';
import { UnstableCompComponentTwoStore } from './components/unstable-comp-two/unstable-comp-two.store';
import { UnstableCompStore } from './components/unstable-comp/unstable-comp.store';
@Injectable({
providedIn: 'root'
})
export class GlobalStateService {
constructor(
private storeUnstableOne: UnstableCompStore,
private storeUnstableTwo: UnstableCompComponentTwoStore
) { }
storeValueOne$ = this.storeUnstableOne.select((state) => state.unstableStateVal);
storeValueTwo$ = this.storeUnstableTwo.select((state) => state.unstableStateValTwo);
combineData(){
const merged = merge(this.storeValueOne$, this.storeValueTwo$)
// merged.forEach(d => console.log(d))
/* value 1 value 2 */
// mergedState = value1 value2
}
}
uj5u.com熱心網友回復:
聽起來你需要combineLatest:
import { combineLatest } from 'rxjs';
const combined = combineLatest([obs1, obs2]);
combined
.subscribe(([latest1, latest2]) => console.log({ latest1, latest2 }));
注意:組合的 observable 只會在每個成員至少發出一次時發出。
從那時起,它會在每次成員發出時發出,為您提供每個可觀察物件的最新值,保持組合可觀察物件的原始順序(因此陣列中的第一個值將是第一個組合可觀察物件的最后一個值)。
在這里可視化它。
在上面的示例中,如果您想將其轉換為每個包含的 observable 的最新值總數的 observable:
combined.pipe(
map(values => values.reduce((o, k) => o k, 0))
)
uj5u.com熱心網友回復:
許多解決方案之一:
import { Component, OnInit } from "@angular/core";
import { merge, of } from "rxjs";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
title = "CodeSandbox";
obs1$ = of(1);
obs2$ = of(2);
ngOnInit() {
let sum = 0;
merge(this.obs1$, this.obs2$).subscribe((a) => {
sum =a
})
console.log(sum)
}
}
在codesandbox上試試
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416714.html
標籤:
上一篇:模態彈出的角度單元測驗
