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

F4K*_*4Ke 0 angular2-routing angular2-services angular2-observables angular

正如标题所解释的那样,当router对象在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));
     }
Run Code Online (Sandbox Code Playgroud)

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

这个过程subscribe完美,但后来 this._router.navigate(['/dashboard']); 给了我:

EXCEPTION:无法读取undefined的属性'navigate'

有任何想法吗 ?

Ale*_*ski 5

您必须使用箭头功能来保留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));
     }
Run Code Online (Sandbox Code Playgroud)