Max*_*Max 3 typescript angular6
我认为这个问题很清楚。我找不到任何有关如何取消订阅 -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()
}
Run Code Online (Sandbox Code Playgroud)
subscribe返回一个Subscription具有unsubscribe方法的对象。您拥有的一种选择是:
public intervallTimer = interval(5000);
private subscription;
ngOnInit() {
this.getValues();
this.subscription = this.intervallTimer.subscribe(() => this.getValues());
}
somefunction(){
this.subscription.unsubscribe()
}
Run Code Online (Sandbox Code Playgroud)
这要求您明确取消订阅,而您可能不想这样做。您还可以考虑 using takeUntil,它返回complete Observable将导致自动unsubscribe. 只要确保这takeUntil是任何链中的最后一个。
public intervallTimer = interval(5000);
private alive = true;
ngOnInit() {
this.getValues();
this.intervallTimer.pipe(takeUntil(() => !this.alive)).subscribe(() => this.getValues());
}
somefunction(){
this.alive = false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8690 次 |
| 最近记录: |