Angular2,取消订阅ngOnDestroy中的事件
参见英文答案 >
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 我该如何避免?如何正确取消订阅? 为了更好的理解,我创建了这个plunker,您可以在控制台中看到错误和一些注释.
你从.subscribe()获得订阅.使用它的unsubscribe()方法取消订阅.
@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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- scala – 如何使用sbtosgi生成osgi bundle作为sbt发布任务的
- WebService传输DataSet的一点想法和实践
- 解决使用bootstrap的dropdown部件时报错:error:Bootstrap
- angularjs – 在DOM渲染之前执行每个摘要循环后的函数
- 使用GET的方式调用WebServices
- -bash: make: command not found的解决办法
- scala – 是否可以使用Apache Spark进行递归计算?
- AngularJS中ng-repeat内的动态过滤器
- twitter-bootstrap – Twitter bootstrap更大的glyphicons.
- scala – 使用IntelliJ 13&SBT播放2.2.2不能运行 – 没