Bogdan Pușcașu
Bogdan Pușcașu

Reputation: 575

Angular 5 - equivalent to $interval from AngularJS

I'm trying to find the equivalent of the $interval from AngularJS into Angular 5.

$interval will repeat a function call or a block a specified number of times with a delay in-between. This is what I would like to do, written in AngularJS:

$interval(function() {
      myFunction(param1, param2)
      i++;
    }, delay, count);

Make abstraction of i, I'm using it for a different purpose. How can this be achieved in Angular 5? I already tried using rxjs/Observable but I can't seem to find a way to include both the delay and the run multiple times part.

Thank you.

Upvotes: 12

Views: 23237

Answers (4)

siva636
siva636

Reputation: 16451

You may make use of the timer static method and take operator.

import {timer} from 'rxjs';
import {take} from 'rxjs/operators';  

timer(yourDelay, 1000).pipe(
   take(yourCount)).subscribe(x=>{
    // do here whatever you want to do here
    })

I assumed you use RxJS 6.

Upvotes: 16

Prashant M Bhavsar
Prashant M Bhavsar

Reputation: 1164

You can refer this tutorial for your query. its working fine in Angular 5 also.. I tried it and its given here simple way.

import { Observable } from “rxjs”;

import { IntervalObservable } from “rxjs/observable/IntervalObservable”;

import { TimerObservable } from “rxjs/observable/TimerObservable”;

import “rxjs/add/operator/takeWhile”;

Declare variable in class
export class MyComponent implements OnInit { 

private alive: boolean; 

}

In ngOnInit() function use below code to call service after particular interval of time
ngOnInit() {

IntervalObservable.create(10000)  .takeWhile(() => this.alive) 
// only fires when component is alive  

.subscribe(() => { this.yourService.getDataList()   
.subscribe(data => { this.agentData = data.json().result; console.log(this.agentData);   });
 });
}

Upvotes: 1

Bk Santiago
Bk Santiago

Reputation: 1573

You can use interval with take to control how many times you want to call your function.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';

const delay = 1000; // every 1 sec
const count = 5; // process it 5 times

Observable.interval(delay).take(count).subscribe(() => {
  myFunction(param1, param2);
});

Upvotes: 4

ashfaq.p
ashfaq.p

Reputation: 5487

You can use interval from rxjs

import { interval } from 'rxjs/observable/interval';

//emit value in sequence every 1 second
const source = interval(1000);
//output: 0,1,2,3,4,5....
const subscribe = source.subscribe(val => console.log(val));

This will emit new value after every 1 second

Upvotes: 3

Related Questions