3

I am trying instantiate a router object and navigate to login if the user is unauthorized usin setTimeout. Problem is when i use the below code system works.

setTimeout(()=>this.router.navigate(['/login']),3000);

But when i change this line to

setTimeout(this.navigateToLogin,3000);

and add

navigateToLogin(){
    console.log("i am in navigate");
    this.router.navigate(['/login']);
}

i get the below error. I am kind of confused. Any help would be appreciated..

TypeError: Cannot read property 'navigate' of undefined

Global error handler

handleError(error){

        console.log(error);
        this.router = this.injector.get(Router)
        switch(error.status){
            case ErrorCodes.UNAUTHORIZED_USER:{
                this._msgService.emitGlobalMessage(new EGlobalModal("Error","Unauthorized User, You will be directed in 3 seconds",false,"red"));
                //setTimeout(()=>this.router.navigate(['/login']),3000);
                setTimeout(this.navigateToLogin,3000);
                break;
            }
            default:{
                this._msgService.emitGlobalMessage(new EGlobalModal("Error",error,false,"red"));
                break;
            }

        }


    }

There are lots of confusing information on the web on the subject. I understand it is the difference between function(){} and arrow function. But i kind of need an explanation. Thanks in advance

rematnarab
  • 1,277
  • 4
  • 22
  • 42

1 Answers1

4

I believe you have a reference error. If u want to use the second method, you will have to bind 'this' to the method call, otherwise this is referring to setTimeout.

setTimeout(this.navigateToLogin.bind(this),3000);
Yoni Affuta
  • 284
  • 1
  • 5