26

How do I call a save function every two minutes in Angular2?

0

1 Answer 1

83

rxjs 6

 import { interval } from 'rxjs'; interval(2000 * 60).subscribe(x => { doSomething(); }); 

rxjs 5

You can either use

import {Observable} from 'rxjs'; // Angular 6 // import {Observable} from 'rxjs/Rx'; // Angular 5 Observable.interval(2000 * 60).subscribe(x => { doSomething(); }); 

or just setInterval()

Hint:

Angular >= 6.0.0 uses RxJS 6.0.0 Angular Changelog 6.0.0

RxJS v5.x to v6 Update Guide

Sign up to request clarification or add additional context in comments.

11 Comments

The interval time isn't rather 12000 (1000ms * 60 * 2), @Günter? ;-)
If you use the .subscribe method, make sure to unsubscribe from it on ngOnDestroy. If you don't then your function will continue to run when the component is destroyed, e.g., navigating away from your component
It should be noted that importing from rxjs/Rx will import the entire rxjs library and increase the size of your deployment bundle. Consider importing only what you need. In this case: import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval';
Angular 6+, should be import {Observable} from 'rxjs';
from ng ^6.1 and rxjs ^6.2 you would have to use it like interval(2000 * 60).subscribe(x => /* do something */)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.