标志变为真时开始轮询

时间:2018-09-18 06:07:26

标签: angular observable rxjs6

我要在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 实现

1 个答案:

答案 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,轮询的频率将增加一倍,并且在销毁组件之后将继续进行某些轮询。