- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个包含 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/
我是一名优秀的程序员,十分优秀!