Function destroys itself after execution?!


#1
constructor( public navCtrl: NavController, private http: Http )
{
	this.getData();
	
	setInterval( function()
	{
		this.getData();
	}, 20000 );
}

getData()
{

	this.http.get('http://localhost:8100/currentPlaying/currentPlaying.php')
	.map((res) => res.json())
	.subscribe(data => {
		this.items = data;
		console.log( data.length );
	}, (rej) => {console.error("Could not load local data",rej)});
}

First this.getData works FINE. 20 seconds later function doesn’t exist anymore (this.getData is undefined, which it CLEARLY isnt). What the hell, this is giving me headaches for hours and hours.

Any help is appreciated.


#2

Try this, the arrow function should fix this:


constructor( public navCtrl: NavController, private http: Http )
{
	this.getData();

	setInterval( () => {
		this.getData();
	}, 20000);
}

getData()
{

	this.http.get('http://localhost:8100/currentPlaying/currentPlaying.php')
	.map((res) => res.json())
	.subscribe((data) => {
		this.items = data;
		console.log( data.length );
	}, (rej) => {console.error("Could not load local data",rej)});
}

This is a problem of scope.


#3

Wow, works fine now. Thanks alot saved me alot of time.


#4

I always use arrows instead function on Intervals and Timeouts functions


#5

Always a pleasure! Would request you to please mark it as the solution so that the thread gets closed… Thanks!


#6

Hi,

Ditch the interval in the constructor, go full on observables to make a poller:

let subscription=Observable
.timer(0,20000)
.switchMap(()=>{
this.http.get('http://localhost:8100/currentPlaying/currentPlaying.php')
	.map((res) => res.json())
})
	.subscribe((data) => {
		this.items = data;
		console.log( data.length );
	}, (rej) => {console.error("Could not load local data",rej)});

Sorry about the formatting

And never ever in your future development carreer type the word function

:slight_smile:

Tom


#7

I’ve fixed the problem! Thanks for the solutions&explanations. Learned something again.