angular2 路由器在订阅方法中变得未定义

angular2 router become undefined in subscribe method

正如标题所解释的那样,router object 在 subscribe 成员内部调用时变为未定义。

让我给你看一些代码:

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

提交表单时调用方法sendLogin()。 表格中的每个变量都很好。

进程完美地达到了subscribe,但是随后 this._router.navigate(['/dashboard']); 给我:

EXCEPTION: Cannot read property 'navigate' of undefined

有什么想法吗?

您必须使用箭头函数来保留 this 上下文。

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

为了避免箭头函数,您可以使用bind绑定this上下文。

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