Reputation: 11407
I am writing a simple angular2 web app that hits an api every 60 secs. I have an api call that i want to schedule call to, everything works well.
How can i call API every 60 secs?
My code
app.componenet (calling class)
constructor(HttpWebServiceService1: HttpWebServiceService1){
HttpWebServiceService1.getHTTP()
.subscribe(//do my stuff here);}
Above calls my api calling class
import { Chart } from './myCode';
@Injectable()
export class HttpWebServiceService1 {
constructor(private http: Http) {}
getHTTP() :Observable<Chart[]> {
//hit the api and get josn string or error
return this.http.get('http://XX.XX.XX.XX/test/test').map((res:Response) => res.json()).catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}
Upvotes: 0
Views: 1727
Reputation: 14201
You can use an interval and then every time the interval emits you can use switchMap to get the result of the http call and then subscribe to it. @snorkpete has a correct answer. If you need to get the data immediately and then every 60 seconds after you can use the concat
operator to get the result immediately and then switch it to the interval like so:
public getData(){
return this.getHttpRequest().concat(
Observable.interval(60000)
.switchMap(() => this.getHttpRequest()));
}
private getHttpRequest(): Observable {
return this.http.get('http://XX.XX.XX.XX/test/test').map(res => {
return res.json();
});
}
Upvotes: 0
Reputation: 14564
The simple way is just to use setInterval
. (see the docs)
you can also leverage RxJS:
Observable.interval(60000)
.switchMap(() => {
// return your http call here
return HttpWebServiceService1.getHTTP()
})
The above will return an observable that tries an http request using your service every 60 secs, and then emits the results of that http request.
Upvotes: 2