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

角度 – 如何订阅事件发射器一次?

发布时间:2020-12-17 07:39:04 所属栏目:安全 来源:网络整理
导读:// Part of servicepublic someEvent: EventEmitternumber = new EventEmitter();....// Component@Component({ selector: 'some-component',template: `...`})export class SomeComponent { constructor(public service: Service) { this.service.someEvent
// Part of service
public someEvent: EventEmitter<number> = new EventEmitter();

....

// Component
@Component({
  selector: 'some-component',template: `...`
})
export class SomeComponent {
  constructor(public service: Service) {
    this.service.someEvent.subscribe((x) => {
      // Do something
    });
  }
}

SomeComponent显示在/ route中.当我在我的应用程序中导航到不同的路由,并再次返回时,SomeComponent将再次订阅该事件,导致回调触发两次.如何订阅事件一次或取消订阅销毁组件并再次订阅?

// Can't subscribe after.
ngOnDestroy() {
  this.service.someEvent.unsubscribe();
}
对订阅的呼叫返回 instance of Disposable,其方法为 dispose.

或者如果您使用的是RxJS 5,dispose has been renamed to unsubscribe(感谢@EricMartinez).

从RxJS docs:

…when we’re no longer interested in receiving the data as it comes streaming in,we call dispose on our subscription.

存储您的呼叫结果以订阅,然后在ngOnDestroy中处理订阅.

RxJS 5:

export class SomeComponent {
  constructor (public service: Service) {
    this.subscription = this.service.someEvent.subscribe((x) => {...});
  }
  ngOnDestroy () {
      this.subscription.unsubscribe();
  }
}

RxJS< 5:

export class SomeComponent {
  constructor (public service: Service) {
    this.subscription = this.service.someEvent.subscribe((x) => {...});
  }
  ngOnDestroy () {
      this.subscription.dispose();
  }
}

(编辑:李大同)

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

    推荐文章
      热点阅读