Angular2,取消订阅ngOnDestroy中的事件 [英] Angular2, unsubsribe from event in 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++;);
}
}
该应用程序具有多个视图(在此示例中只有两个):PageA
和PageB
. EmitterComponent
和ReceiverComponent
在PageA
中.每次我进入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.
为避免这种情况,我从ngOnDestroy
的myEvent
取消订阅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();
}
}
另请参见
这篇关于Angular2,取消订阅ngOnDestroy中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!