我要在atrribute的值变为true时开始轮询,是否有任何方法在标志变为true时开始轮询,现在我的实现是:
ngOnInit(){
//want to start when startedPoll becomes true otherwise dont
let url = 'getStatus'
this.pollingSubscribe = interval(5000).pipe(
switchMap(() => this.http.getCall(url))
).subscribe(data => {
if(data['success']) {
this.pollingData =data['result']
this.processData(this.pollingData)
}
}, error =>{
this.error = true;
this.errorData = this.createPollingFiles;
})
}
startPoll(){
this.startedPoll = true;
}
当 startedPoll 变为 true 开始轮询数据时,请不要建议 if and else 实现
答案 0 :(得分:2)
如果startedPoll
成为true
的唯一方法是调用startPoll
方法时,只需将subscribe
方法中的ngOnInit
调用移至startPoll
:
ngOnInit() {
// want to start when startedPoll becomes true otherwise dont
let url = 'getStatus'
this.pollingObservable = interval(5000).pipe(
switchMap(() => this.http.getCall(url))
);
}
startPoll() {
this.pollingSubscribe = this.pollingObservable.subscribe(data => {
if (data['success']) {
this.pollingData = data['result']
this.processData(this.pollingData)
}
}, error => {
this.error = true;
this.errorData = this.createPollingFiles;
})
this.startedPoll = true;
}
ngOnDestroy() {
if (this.pollingSubscribe) {
this.pollingSubscribe.unsubscribe();
}
}
确保在进行轮询时不会多次调用startPoll
。否则,将丢失已经存储在Subscription
中的this.pollingSubscribe
,轮询的频率将增加一倍,并且在销毁组件之后将继续进行某些轮询。