【问题标题】:How to Stop observable.timer in Angular2如何在 Angular2 中停止 observable.timer
【发布时间】:2017-10-17 18:25:26
【问题描述】:

我在Angular2的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;
  }
}

一旦值与setFormData() 正确存储,我想停止重复Observable.timer

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

【问题讨论】:

  • 所以你想在执行一次后停止它?或者您是否在等待 this.authStore.registerInfo 数据被设置在某处,因此您需要继续调用 setFormData 直到数据到达?
  • 如果你知道接收数据需要多少时间,为什么不使用延迟之类的运算符。
  • 这样做似乎不是一个好主意。如果您提供有关您要实现的目标的更多信息,也许我们可能会指出另一个方向来处理您的问题

标签: javascript angular typescript rxjs rxjs5


【解决方案1】:

基本上有两种方式:

  • 在从subscribe() 调用返回的订阅对象上调用unsubscribe()
  • 使用运算符

对于unsubscribe,您可以这样做。

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

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

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

this.subject = new Subject();

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

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

也看看这些:

2019 年 1 月:针对 RxJS 6 更新

【讨论】:

  • 我不知道我们可以在订阅块内取消订阅。很高兴知道。
【解决方案2】:

当您想像这样停止可观察的计时器时,可以使用unsubscribe 方法

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

.............
this.subscription.unsubscribe();

【讨论】:

  • 为什么这么多反对票?这个答案错了​​吗?甚至@martin 的答案与我发布的代码相同
  • 是的。 unsubscribeSubscription 上调用,而不是在 Observable 上调用。
  • okii 但答案没有提供任何错误信息,对吗?毕竟你必须使用取消订阅方法吗?比为什么要投反对票?
  • 我知道代码是正确的,但我认为没有什么不同,仍然感谢您让我知道我已经编辑了我的答案
  • hmm @cartant 可能你是对的,我只是在测试之前发布代码,我认为这是我的错误
【解决方案3】:

以前的答案没有真正涵盖的细微差别是,没有必要停止可观察的计时器/间隔 - 至少不需要与可观察的或计时器本身交互。

我发现自己在这里是因为我在 HostedService 的 start 方法中使用计时器设置了一个 observable,而在 stop 方法中 似乎 我应该停止它,或者处理肯定有什么? - 嗯……不。 observable timer 不需要以这种方式停止或处置,只需要订阅,这就是为什么...

可观察的计时器和间隔是冷流的示例(尽管它们看起来像热流)。它们是被动的而不是主动的,它们在订阅之前不会产生数据,并且在没有订阅者时停止产生数据。因此,处理所有订阅应该是停止计时器生成数据所需的全部内容。

更多信息在这里... [http://introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html]

【讨论】:

    【解决方案4】:

    xD 你知道你可以做出承诺吗?

    import { timer } from 'rxjs';
    
    timer(1000).toPromise().then(res => {
          //code here  
    })
    

    无需处理退订。

    【讨论】:

      【解决方案5】:

      -- 解决方法

      setTimeout(() => observable.next(null) , 2000);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多