加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2,取消订阅ngOnDestroy中的事件

发布时间:2020-12-17 09:15:16 所属栏目:安全 来源:网络整理
导读:参见英文答案 How to cancel a subscription in Angular26 在我的应用程序中,我有一些通过EventService进行通信的组件. @Injectable()export class EventService { public myEvent: EventEmitterany = new EventEmitter(); constructor() {}} 这个服务被注入
参见英文答案 > 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
> timer.unsubscribe is not a function Angular2

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读