Angular 6 - run method in service every 10 seconds

前端 未结 7 1954
难免孤独
难免孤独 2020-12-14 02:52

I have this service using HttpClient to get some data :

checkData() {
    return this.http.get(\'my url\');
}

The on the footer component I

7条回答
  •  独厮守ぢ
    2020-12-14 03:38

    Use rxjs timer to call the api request at startup and then every 10s.

    This is best achieved by using rxjs to divide and conquer.

    Firstly, import the following:

    import { timer, Observable, Subject } from 'rxjs';
    import { switchMap, takeUntil, catchError } from 'rxjs/operators';
    

    Then add the property to handle request to the api:

    private fetchData$: Observable = this.myservice.checkdata();
    

    Next, add the property to handle the timing:

    private refreshInterval$: Observable = timer(0, 1000)
    .pipe(
      // This kills the request if the user closes the component 
      takeUntil(this.killTrigger),
      // switchMap cancels the last request, if no response have been received since last tick
      switchMap(() => this.fetchData$),
      // catchError handles http throws 
      catchError(error => of('Error'))
    );
    

    At last, fire the kill command if the component is killed:

    ngOnDestroy(){
      this.killTrigger.next();
    }
    

    Here is a StackBlitz Demo.

提交回复
热议问题