Alex Alex - 4 months ago 77
TypeScript Question

Angular 2 call setInterval() undefined Services form Dependency injection

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);


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);