Angular2,取消订阅ngOnDestroy中的事件 [英] Angular2, unsubsribe from event in ngOnDestroy

查看:98
本文介绍了Angular2,取消订阅ngOnDestroy中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一些通过EventService进行通信的组件.

In my application I have some components that communicate by means of EventService.

@Injectable()
export class EventService {
  public myEvent: EventEmitter<any> = new EventEmitter();
  constructor() {}
}

此服务被注入到EmitterComponent中,该事件在单击按钮时会发出事件

This service is injected in a EmitterComponent that emits the event when a button is clicked

@Component({
  selector: 'emitter',
  template: `<button (click)="onClick()">Click me</button>`,
})
export class EmitterComponent {
  constructor(private eventService:EventService) {}
  onClick() {
    this.eventService.myEvent.emit();
  }
}

,并在预订该事件的ReceiverComponent中,并且对于收到的每个事件,都会增加一个计数器

and in a ReceiverComponent that subscribes to the event and for each event received increments a counter

@Component({
  selector: 'receiver',
  template: `Count: {{count}}`,
})
export class ReceiverComponent {
  public count = 0;
  constructor(private eventService:EventService) {
    this.eventService.myEvent.subscribe(() => this.count++;);
  }
}

该应用程序具有多个视图(在此示例中只有两个):PageAPageB. EmitterComponentReceiverComponentPageA中.每次我进入PageB并返回到PageA时,都会创建一个新的ReceiverComponent,并且当我单击EmitterComponent中的按钮时,会多次执行ReceiverComponent的事件回调函数.

The application has multiple views (in this example just two): PageA and PageB. EmitterComponent and ReceiverComponent are in PageA. Every time I go to PageB and come back to PageA, a new ReceiverComponent is created and when I click the button in EmitterComponent, the event callback function of ReceiverComponent is executed several times.

为避免这种情况,我从ngOnDestroymyEvent取消订阅ReceiverComponent

To avoid this I unsubscribe ReceiverComponent from myEvent in ngOnDestroy

ngOnDestroy() {
  this.eventService.myEvent.unsubscribe();
}

但这会导致以下异常

EXCEPTION: Error during instantiation of ReceiverComponent!.
ORIGINAL EXCEPTION: Error: Cannot subscribe to a disposed Subject

如何避免这种情况?如何正确退订?

How can I avoid that? How to unsubscribe correctly?

为了更好地理解,我创建了这个 plunker ,您可以在其中看到错误以及控制台中的一些注释.

For a better understanding I've created this plunker where you can see the error and some comments in the console.

推荐答案

您从.subscribe()获得订阅.使用其unsubscribe()方法取消订阅.

You get a subscription from .subscribe(). Use its unsubscribe() method to cancel the subscription.

@Component({
  selector: 'receiver',
  template: `Count: {{count}}`,
})
export class ReceiverComponent {
  public count = 0;
  private subscription;
  constructor(private eventService:EventService) {
    this.subscription = this.eventService.myEvent.subscribe(() => this.count++;);
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

另请参见

timer.unsubscribe不是Angular2函数

这篇关于Angular2,取消订阅ngOnDestroy中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆