本文介绍了如何以角度2取消订阅多个订阅者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有另一个组件的shareService和订阅:

I have shareService and subscribe that is in another components :

import { Component, Input, OnDestroy } from '@angular/core';
import { MissionService } from './mission.service';
import { Subscription }   from 'rxjs/Subscription';
@Component({
  selector: 'my-astronaut',
  template: `
    <p>
      {{astronaut}}: <strong>{{mission}}</strong>
      <button
        (click)="confirm()"
        [disabled]="!announced || confirmed">
        Confirm
      </button>
    </p>
  `
})
export class AstronautComponent implements OnDestroy{
  @Input() astronaut: string;
  mission = "<no mission announced>";
  confirmed = false;
  announced = false;
  subscription:Subscription;

  constructor(private missionService: MissionService) {
    this.subscription = missionService.missionAnnounced$.subscribe(
      mission => {
        this.mission = mission;
        this.announced = true;
        this.confirmed = false;
    })




  }
  confirm() {
    this.confirmed = true;
    this.missionService.confirmMission(this.astronaut);
  }
  ngOnDestroy(){
    // prevent memory leak when component destroyed
    this.subscription.unsubscribe();

  }
}

我想知道我是否有我的构造函数中的2个订阅者,如何取消订阅ngDestroy中的两个订阅者?
我应该使用 subscription2:订阅; ?和ngDestroy this.subscription2.unsubscribe();
这是真的吗?

I want to know if I have 2 subscribers in my constructor, how to unsubscribe twice subscribers in ngDestroy?I should use subscription2:Subscription;?and in ngDestroy this.subscription2.unsubscribe();?this is true?

推荐答案

您可以在数组中的ngOnDestroy()

export class AstronautComponent implements OnDestroy{
  @Input() astronaut: string;
  mission = "<no mission announced>";
  confirmed = false;
  announced = false;
  subscriptions:Subscription[] = [];

  constructor(private missionService: MissionService) {
    this.subscriptions.push(missionService.missionAnnounced$.subscribe(
      mission => {
        this.mission = mission;
        this.announced = true;
        this.confirmed = false;
    }));

    this.subscriptions.push(fooService.fooObservable$.subscribe(
      ...
    }));
  }

  confirm() {
    this.confirmed = true;
    this.missionService.confirmMission(this.astronaut);
  }

  ngOnDestroy(){
    // prevent memory leak when component destroyed
    this.subscriptions.forEach(s => s.unsubscribe());
  }
}

这篇关于如何以角度2取消订阅多个订阅者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:14