Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 call setInterval() undefined Services form Dependency injection

Tags:

I want to call a function every 10 minutes by using setInterval() and in this function I want to use a Service (called auth) that I get from the Dependency Injector of Angular 2, the problem is that the console tells me following:

EXCEPTION: TypeError: this.auth is undefined

  constructor(private auth: AuthService){     setInterval(function(){ this.auth.refreshToken(); }, 1000 * 60 * 10);   } 
like image 746
Alex Avatar asked Mar 06 '16 15:03

Alex


1 Answers

this in the function given to setInterval doesn't point to the class when it is called.

Use arrow function instead.

 constructor(private auth: AuthService){     setInterval(() => { this.auth.refreshToken(); }, 1000 * 60 * 10);   } 
like image 72
toskv Avatar answered Oct 08 '22 05:10

toskv