NGRX 正确使用商店选择器

NGRX correct usage of store selectors

我在我的应用程序中使用 Ngrx 来存储状态。 假设我的商店有两个项目 itemA 和 itemB。 我的 componentX 对 itemA 的变化做出反应并触发一个函数,该函数进一步进行一些更复杂的计算,需要 itemB

的当前值
ComponentX {
    pi = 3.15;
    date = new Date();
    constructor(private appStore: Store<AppState>){}
    ngOnInit() {
         this.appstore.select(selectItemA).subscribe(
             (itemA) => someComplexFunction(itemA)
         )
    }
    someComplexFunction(itemA) {
        /* Requires itemB */
    }
}

然而componentX并不关心itemB何时变化,它只需要itemA变化时itemB的当前值。我无法从我的状态中删除 itemB,因为其他组件需要它。 在这种情况下编写选择器的正确方法是什么。

您可以使用 withLatestFrom 运算符。

类似 withLatestFrom(this.appstore.select(selectItemB)) 的东西会给你 B.

看看这个例子,在效果中做了同样的事情: https://gist.github.com/vteivans/da5adf19a94da9e32d27cb8b9d5b8884

(原理相同)