簡體   English   中英

如何在angular 7 FormGroup valueChanges中刪除多個訂閱列表中的特定訂閱?

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

我正在使用angular 7 Multiple FormControl valueChanges訂閱功能。

如何刪除或取消訂閱特定的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);
}

我希望刪除的控件取消訂閱;

鑒於您沒有將control.valueChanges.subscribe分配給任何變量,您不能。

此外,此代碼將導致嚴重的內存泄漏。 您永遠不會關閉訂閱,這是一種非常危險的方式來管理它們。

您可以使用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();
}

或者您可以將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