我认为这个问题很清楚。我找不到有关如何取消订阅 rsjx 之类的 interval or timer 操作的任何信息?

我的组件:

public intervallTimer = interval(5000);

ngOnInit() {
  this.getValues();
  this.intervallTimer.subscribe(() => this.getValues());
}

// What I like to do is something like this, but "unsubscribe()" that's no function
somefunction(){
  this.intervallTimer.unsubscribe()
}

最佳答案

subscribe 返回一个以 Subscription 作为方法的 unsubscribe 对象。您拥有的一种选择是:

public intervallTimer = interval(5000);
private subscription;

ngOnInit() {
  this.getValues();
  this.subscription = this.intervallTimer.subscribe(() => this.getValues());
}

somefunction(){
  this.subscription.unsubscribe()
}

这要求您明确取消订阅,而您可能不想这样做。您还可以考虑使用 takeUntil ,它返回一个 complete Observable ,这将导致自动 unsubscribe 。只要确保 takeUntilthe last in any chain
public intervallTimer = interval(5000);
private alive = true;

ngOnInit() {
  this.getValues();
  this.intervallTimer.pipe(takeUntil(() => !this.alive)).subscribe(() => this.getValues());
}

somefunction(){
  this.alive = false;
}

关于typescript - 角 6 : How to unsubscribe rsjx interval or timer?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51845697/

10-09 22:23