【发布时间】:2020-12-09 06:43:46
【问题描述】:
我正在从父级传递一些 @Input 道具,每当我的道具更新时,我希望我的组件也更新。
我在做的是这样的:
@Input() variable;
@Input() variable2;
public deets;
constructor() {
this.details$ = this._sore.select("details")
}
ngOnInit() { }
ngOnChanges(changes: SimpleChanges) {
if (
changes.variable && changes.variable.currentValue ||
changes.variable2 && changes.variable2.currentValue
) {
this.apiCall();
this.subscribeMethod();
}
}
ngOnDestroy() {
this.deets.unsubscribe();
}
subscribeMethod() {
this.deets = this.details$.subscribe(value => {
if (value) // this.action1()
}
}
apiCall() {
this._store.dispatch(new LoadDetailsAction);
}
action1() { console.log("test") }
但是我注意到,当我从父级更改我的 Input 道具并更新时,我正在进行一次 API 调用(很好),但看起来我又在订阅了?所以我有某种内存泄漏。
如果在我的 this.action1() 中创建控制台日志,第一次,它将记录一次。然后,如果我再次更新我的变量或变量 2,它会控制台记录两次。然后三次。等等
是因为我的订阅没有被删除吗?所以它在多个订阅中调用 action1?
我以为我的 ngOnDestroy() 会解决这个问题,但我猜因为组件实际上并没有被销毁而是更新,所以它没有解决它。
那么我会将我的 subscribeMethod 移动到 onInit 吗?进入我的构造函数?如何避免这些过度操作?
谢谢!
编辑我尝试将我的 subscribeMethod 移动到我的 ngOnInit ,它似乎解决了问题,但它给了我两次控制台日志。一次使用旧订阅数据,一次使用新订阅数据:(
【问题讨论】:
标签: angular