如何在Angular2中停止observable.timer [英] How to Stop observable.timer in Angular2

查看:483
本文介绍了如何在Angular2中停止observable.timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2的组件中实现了以下功能:

I am implementing the following functions in Angular2's Component:

export class MypageEditComponent {

  ngOnInit() {
    this.timer = Observable.timer(100, 100);
    this.timer.subscribe(t => {
      this.setFormData();
  }


  private setFormData() {
    this.editUserAcountType = this.authStore.registerInfo.account_type;
    this.editAddress = this.authStore.registerInfo.email;
    this.editUserName = this.authStore.registerInfo.username;
  }
}

我想停止重复 Observable.timer 一旦使用 setFormData()正确存储该值。

I want to stop the repeat of Observable.timer once the value is correctly stored with setFormData().

但不知道怎么样,请告诉我。

But do not know how, please tell me.

推荐答案

基本上有两种方式:


  • subscribe() unsubscribe() >打电话。

  • 使用运算符

  • call unsubscribe() on the Subscription object returned from the subscribe() call .
  • use an operator

只需取消订阅你可以这样做。

ngOnInit() {
  this.subscription = timer(100, 100).subscribe(t => {
    this.setFormData();
  });
}

private setFormData() {
  ...
  this.subscription.unsubscribe();
}

或者您可以使用Subject通过完成Observable takeUntil() operator:

Or you can use Subject to complete the Observable via takeUntil() operator:

this.subject = new Subject();

ngOnInit() {
  timer(100, 100).pipe(
    takeUntil(this.subject),
  ).subscribe(t => this.setFormData());
}

private setFormData() {
  ...
  this.subject.next();
}

看看这些:

  • Difference between .unsubscribe to .take(1)
  • RxJS: takeUntil() Angular component's ngOnDestroy()

2019年1月:更新为RxJS 6

Jan 2019: Updated for RxJS 6

这篇关于如何在Angular2中停止observable.timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆