javascript - 我应该取消订阅 Angular 表单更改吗?
问题描述
使用valueChanges订阅Angular 抽象控件中的更改时,是否有必要?unsubscribe()
我经常这样做:
// this.form is a FormGroup within a Component.
this.form.valueChanges.subscribe(_ => {
console.log(this.form.value);
});
但是我应该自己管理订阅吗(就像我ngrx
一般做的那样)?:
import { Subscription } from 'rxjs';
// this.subscription is ngrx Subscription.
this.subscription = this.form.valueChanges.subscribe(_ => {
console.log(this.form.value);
});
public ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
我之前没有这样做的唯一原因是,Angular Forms 上的教程、示例和文档通常会省略存储对订阅的引用,而是按原样使用valueChanges 。
相反,ngrx 教程似乎强调了取消订阅以避免内存泄漏的重要性。
解决方案
是的,这是必要的,但您可以使用 take until 代替。
private unsubscribe$: Subject<void> = new Subject<void>();
this.subscription = control.valueChanges
pipe(takeUntil(this.unsubscribe$))
.subscribe(_ => {
console.log(this.form.value);
});
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
推荐阅读
- pyomo - 根据 Pyomo 中的变量值更改约束
- c# - Is there some way to have Newtonsoft.Create call your custom creation method on an interface?
- vue.js - 模板中的道具未与 VueJS 一起显示
- jquery - 如何在 jQuery 中设置切换屏幕的常用速度
- magento-1.9 - 购物车规则对不同产品应用固定折扣
- intellij-idea - 无法加载 jvm dll C:\Program Files\JetBrains\Intelij IDEA Community EDItio 2018.2.2\jre64\\bin\server\jvm.dll
- react-native - 本机基础中的多个输入
- ios - 显示最近的问题 clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)?
- haskell - Haskell 乘法索引
- javascript - 打字稿错误:“RRule”仅指一种类型,但在此处用作命名空间