简体   繁体   English

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

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

Created the component with multiple subscription, also on ngOnDestroy doing the unsubscribe. 创建了具有多个订阅的组件,也对ngOnDestroy进行了取消订阅。

It's working as expected but created the multiple variable for each subscription, how can i do with single variable like pushing in to array or json? 它按预期工作,但为每个订阅创建了多个变量,我该如何处理单个变量,例如推入数组或json?

tried below logic 尝试以下逻辑

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

Pushed all the subscribes by key value, if any key value missing or mismatched may error come. 按键值推送所有订阅,如果任何键值丢失或不匹配,可能会出现错误。

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

Is the any better way to implement this? 有没有更好的方法来实现这一目标?

You can create one Subscription object and add everything into it using its add method. 您可以创建一个Subscription对象,并使用其add方法将所有内容添加到其中。

this.subscriptions = new Subscription();

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

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

And then unsubscribe everything: 然后退订所有内容:

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

Maybe a also have a look at this: https://github.com/ReactiveX/rxjs/issues/2769 也许还可以看看这个: https : //github.com/ReactiveX/rxjs/issues/2769

Use TakeUntil: 使用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