简体   繁体   English

如何在angular 7 FormGroup valueChanges中删除多个订阅列表中的特定订阅?

[英]how to remove specific subscribe in multiple subscribes list in angular 7 FormGroup valueChanges?

I am using angular 7 Multiple FormControl valueChanges subscribe function. 我正在使用angular 7 Multiple FormControl valueChanges订阅功能。

how do I remove or unsubscribe specific FormControl subscribe function. 如何删除或取消订阅特定的FormControl订阅功能。

FormControlsSubscribe(){
  const FormControlsArray = Object.keys(this.FGroup.controls);
     FormControlsArray.map(controlName => {
     const control = this.FGroup.controls[controlName] as FormControl;
     control.valueChanges.subscribe(change => {
        console.log(controlName + '>>>' + change);
     });
  });
};



RemoveControl(ControlKey: any) {
  this.FGroup.removeControl(ControlKey);
}

I expect the removed control unsubscribed; 我希望删除的控件取消订阅;

Given that you don't assign control.valueChanges.subscribe to any variable, you can't. 鉴于您没有将control.valueChanges.subscribe分配给任何变量,您不能。

Moreover, you will have severe memory leaks with this code. 此外,此代码将导致严重的内存泄漏。 You never close your subscriptions, this is a very dangerous way to manage them. 您永远不会关闭订阅,这是一种非常危险的方式来管理它们。

You can use takeUntil to unsubscribe automatically: 您可以使用takeUntil自动取消订阅:

private unsubscribe$: Subject<void> = new Subject<void>();

control.valueChanges
pipe(takeUntil(this.unsubscribe$))
.subscribe(_ => {
  console.log(controlName + '>>>' + change);
});

ngOnDestroy() {
  this.unsubscribe$.next();
  this.unsubscribe$.complete();
}

or you can assign control.valueChanges.subscribe to a variable (Subscription) and unsubscribe that. 或者您可以将control.valueChanges.subscribe分配给变量(订阅)并取消订阅。

let subs: Subscription[] = [];

FormControlsArray.map(controlName => {
  const control = this.FGroup.controls[controlName] as FormControl;
  this.subs.push(control.valueChanges.subscribe(() => {}));
});

ngOnDestroy() {
  this.subs.forEach(sub => sub.unsubscribe());
  this.subs = [];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM