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

时间:2018-04-03 11:38:09

标签: angular rxjs

创建具有多个订阅的组件,同样在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();
    }
}

有没有更好的方法来实现这个?

2 个答案:

答案 0 :(得分:2)

您可以创建一个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

答案 1 :(得分:1)

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