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

时间:2016-10-27 09:46:52

标签: angular angular2-routing angular2-services angular2-observables

正如标题所解释的那样,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));
     }

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

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

  

EXCEPTION:无法读取undefined

的属性'navigate'

任何想法?

2 个答案:

答案 0 :(得分: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));
     }

答案 1 :(得分:0)

要避免使用箭头功能,您可以使用bind绑定this上下文。

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