Angular 6 - run method in service every 10 seconds

user9597092 picture user9597092 · May 29, 2018 · Viewed 40.6k times · Source

I have this service using HttpClient to get some data :

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

The on the footer component I call it and display the result :

ngOnInit() {
    this.myservice.checkdata().subscribe( result => { this.statustext = result } );
}

This works, but I need this method to be run every 10 seconds so it's up to date.

How can I do this?

Answer

Adrien SAULNIER picture Adrien SAULNIER · May 29, 2018

Try with timer from RxJS :

import { Subscription, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';

subscription: Subscription;
statusText: string;

ngOnInit() {
    this.subscription = timer(0, 10000).pipe(
      switchMap(() => this.myservice.checkdata())
    ).subscribe(result => this.statustext = result);
}

ngOnDestroy() {
    this.subscription.unsubscribe();
}

interval(10000) from RxJS is not appropriate, because it will start to emit values ONLY after 10sec and not immediatly for the first time (and I think that's not what you're looking for).

However, timer(0, 10000), will emit values immediatly (0) and every 10sec (10000) until unsubscription.