angular2 router become undefined in subscribe method

倾然丶 夕夏残阳落幕 提交于 2019-12-25 07:41:13

问题


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 ?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/40281375/angular2-router-become-undefined-in-subscribe-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!