繁体   English   中英

如何将所有组件订阅分配为单个变量(如数组)并取消订阅所有内容

[英]How to assign all the component subscription into single variable like array and unsubscribe everything

创建了具有多个订阅的组件,也对ngOnDestroy进行了取消订阅。

它按预期工作,但为每个订阅创建了多个变量,我该如何处理单个变量,例如推入数组或json?

尝试以下逻辑

this.sub[1] = this.crossCommunicate.toggleEdit.subscribe(
      (showedit: any) => {
         this.showedit = showedit;
      }
    );

按键值推送所有订阅,如果任何键值丢失或不匹配,可能会出现错误。

ngOnDestroy() {
    for(let i=1; i < this.sub.length ; i++){
      this.sub[i].unsubscribe();
    }
}

有没有更好的方法来实现这一目标?

您可以创建一个Subscription对象,并使用其add方法将所有内容添加到其中。

this.subscriptions = new Subscription();

const sub1 = this.whatever$.subscribe(...);
const sub2 = this.foobar$.subscribe(...);

this.subscriptions
  .add(sub1)
  .add(sub2);

然后退订所有内容:

ngOnDestroy(): void {
  this.subscriptions.unsubscribe();
}

也许还可以看看这个: https : //github.com/ReactiveX/rxjs/issues/2769

使用TakeUntil:

import 'rxjs/add/operator/takeUntil';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

export class APPcomponent implements OnInit, OnDestroy {
    private ngUnsubscribe: Subject<any> = new Subject();
    }

ngOnInit() { 
    this.someService.SomeCall(parametesr)
        .takeUntil(this.ngUnsubscribe)
        .subscribe(
            data => {
                some result
            },
            error => { },
            () => {
            });

    this.someService.SecondCall(parametesr)
        .takeUntil(this.ngUnsubscribe)
        .subscribe(
            data => {
                some result
            },
            error => { },
            () => {
            });

}

someProcedure() {
this.someService.ThirdCall(parametesr)
        .takeUntil(this.ngUnsubscribe)
        .subscribe(
            data => {
                some result
            },
            error => { },
            () => {
            });
}


ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
    }

暂无
暂无

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

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