Search code examples
angularangular2-routingangular2-servicesangular2-observables

angular2 router become undefined in subscribe method


As the title explains it, the router object become undefined when it's called inside a subscribe member.

Let me show you some code:

export class AuthComponent implements OnInit {
   password = '';
   email = ''; 

  constructor(
      private _router: Router,
      private authService: AuthService
  ) { }


  sendLogin(): void {
       this.authService.login(this.email, this.password)
                   .subscribe(function(token){
                     console.log("Success Response" + token)
                     this.token = token
                     // TOKEN Here is good
                     // now I want to change my page, but
                     // _router -> undefined
                     this._router.navigate(['/dashboard']);

                   },
                     error =>  console.log(error));
     }

the method sendLogin()is called when submitting a form. every varibales from the form are good.

The process reach the subscribe perfectly, but then this._router.navigate(['/dashboard']); gives me :

EXCEPTION: Cannot read property 'navigate' of undefined

any ideas ?


Solution

  • You have to use an arrow function to preserve the this context.

    sendLogin(): void {
           this.authService.login(this.email, this.password)
                       .subscribe( token => {
                         console.log("Success Response" + token)
                         this.token = token
                         // TOKEN Here is good
                         // now I want to change my page, but
                         // _router -> undefined
                         this._router.navigate(['/dashboard']);
    
                       },
                         error =>  console.log(error));
         }