gpt4 book ai didi

ngrx/store subscribe 被多次调用。退订的最佳地点?

转载 作者:行者123 更新时间:2023-12-01 05:08:37 25 4
gpt4 key购买 nike

我有一个包含 NgModal 弹出窗口的角度组件。

我正在订阅组件中的 ngrx 商店。

组件的 ngOnDestroy 永远不会被调用,因为新路由永远不会被调用。

用户通过模态弹出窗口添加新用户。

“用户”状态下对商店的订阅(选择)永远不会取消订阅,并且会被多次调用。

当从不调用 ngOnDestroy() 时,处理从 store.select() 取消订阅的最佳方法是什么?

最佳答案

解决此问题的最简单方法是不要在您的组件中订阅,而是通过async 管道在模板中执行。

来自Angular Docs :

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks (emphasis added).

既然你提到 ngOnDestroy 没有被调用,那么组件很可能会持续存在并根据需要隐藏/显示,在这种情况下你只会获得单个订阅。

您还可以通过使用“async as”模式来阻止模板中的多个subscribe 调用,as explained by Todd Motto here. .基本上,当遇到模板中需要多个 async 管道时,在更高的元素上使用 *ngIf="data$ | async as data" 并引用已解析的 数据如下。

关于ngrx/store subscribe 被多次调用。退订的最佳地点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com