Angular 6 - run method in service every 10 seconds

前端 未结 7 1976
难免孤独
难免孤独 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:33

    In your checkData method you could do something like this:

    import { timer, of } from 'rxjs';
    import { switchMap, catchError } from 'rxjs/operators';
    
    checkData() {
        return timer(0, 10000)
            .pipe(
               switchMap(_ => this.http.get('my url')),
               catchError(error => of(`Bad request: ${error}`))
            );
    }
    

    Then your subscribe will get the result of the http call every 10 seconds.

提交回复
热议问题