[英]How to Stop observable.timer in Angular2
我正在 Angular2 的組件中實現以下功能:
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
的重復。
但不知道如何,請告訴我。
基本上有兩種方式:
subscribe()
調用返回的 Subscription 對象調用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 更新
當您想像這樣停止可觀察的計時器時,您可以使用unsubscribe
方法
this.timer = Observable.timer(100, 100);
this.subscription = this.timer.subscribe(t => {
this.setFormData();
});
.............
this.subscription.unsubscribe();
以前的答案沒有真正涵蓋的一個細微差別是,不需要停止可觀察的計時器/間隔 - 至少不需要與可觀察的或計時器本身進行交互。
我發現自己在這里是因為我在 HostedService 的 start 方法中使用計時器設置了一個 observable,而在 stop 方法中,我似乎應該停止它,或者肯定地處理一些東西? - 嗯……不。 observable timer 不需要以這種方式停止或處理,只需要訂閱,這就是為什么......
可觀察的計時器和間隔是冷流的例子(盡管它們看起來像熱流)。 它們是被動的而不是主動的,它們在訂閱之前不會產生數據,並且在沒有訂閱者時停止產生數據。 因此,處理所有訂閱應該是停止計時器生成數據所需的全部內容。
更多信息在這里... [ http://introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html]
xD 你知道你可以做出承諾嗎?
import { timer } from 'rxjs';
timer(1000).toPromise().then(res => {
//code here
})
無需處理退訂。
-- 解決方法
setTimeout(() => observable.next(null) , 2000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.