【问题标题】:NGRX correct usage of store selectorsNGRX 正确使用存储选择器
【发布时间】:2018-09-22 14:15:55
【问题描述】:

我在我的应用程序中使用 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 何时发生变化,它只需要 itemB 在 itemA 发生变化时的当前值。我无法从我的状态中删除 itemB,因为其他组件需要它。 在这种情况下编写选择器的正确方法是什么。

【问题讨论】:

  • 您可以订阅 itemA 选择器,并使用 itemB 选择器通过withLatestFrom 进行管道传输
  • 你能给我们更多关于someComplexFunction的信息吗?它是纯函数还是有副作用?如果它是一个纯函数,那么你应该完全为它编写另一个选择器。
  • @maxime1992: 它不是一个纯函数
  • Dee zg 的答案是正确的。

标签: angular ngrx ngrx-store


【解决方案1】:

您可以使用withLatestFrom 运算符。

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

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

(原理相同)

【讨论】:

  • 下面的代码未定义 val this.appstore.select(selectItemA).pipe(withLatestFrom(selectItemB)).subscribe((val) => console.log(val))
  • 我意识到这个错误让它现在可以工作了。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 2021-01-22
  • 2022-04-21
  • 2022-08-18
  • 2019-02-06
  • 1970-01-01
相关资源
最近更新 更多