参见英文答案 >
How to cancel a subscription in Angular26
在我的应用程序中,我有一些通过EventService进行通信的组件.
@Injectable() export class EventService { public myEvent: EventEmitter<any> = new EventEmitter(); constructor() {} }
这个服务被注入到一个EmitterComponent中,当点击一个按钮时会发出这个事件
@Component({ selector: 'emitter',template: `<button (click)="onClick()">Click me</button>`,}) export class EmitterComponent { constructor(private eventService:EventService) {} onClick() { this.eventService.myEvent.emit(); } }
并在一个ReceiverComponent中订阅该事件,并且每个收到的事件都会增加一个计数器
@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的事件回调函数被执行了好几次.
为了避免这种情况,我在ngOnDestroy中从myEvent取消订阅ReceiverComponent
ngOnDestroy() { this.eventService.myEvent.unsubscribe(); }
但这会导致以下异常
EXCEPTION: Error during instantiation of ReceiverComponent!. ORIGINAL EXCEPTION: Error: Cannot subscribe to a disposed Subject
我该如何避免?如何正确取消订阅?
你从.subscribe()获得订阅.使用它的unsubscribe()方法取消订阅.
原文链接:https://www.f2er.com/angularjs/140765.html@Component({ selector: 'receiver',}) export class ReceiverComponent { public count = 0; private subscription; constructor(private eventService:EventService) { this.subscription = this.eventService.myEvent.subscribe(() => this.count++;); } ngOnDestroy() { this.subscription.unsubscribe(); } }
也可以看看
> how to unsubscribe several subscriber in angular 2
> timer.unsubscribe is not a function Angular2