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);
}
A full discussion of this issue can be found in the documentation for the setInterval() method, captioned The "this" Problem. About halfway down the page.
The jist is that it is the result of a change in the "this" variable. The function being passed into the setInterval() function is extracted from the class context and placed into the context of setInterval() (the window). So, it is undefined.
There are several solutions to this issue. The method proposed by toskv above is a fairly common approach. Another solution is to use the bind() method.
Reference material from this question, answer by Pointy.
Documentation for the bind() method.
A good article on javascript scope, which can still come back to bite you in typescript.
this in the function given to setInterval doesn't point to the class when it is called.
Use arrow function instead.
There's a little trick for solving that. Hope this helps.
First do
then