简体   繁体   中英

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 ?

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

To avoid arrow function, you can use bind to bound the this context.

// ...
this.authService.login(this.email, this.password)
  .subscribe(function(token){ //.. your code }.bind(this),
    error => console.log(error));
} // ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM