简体   繁体   English

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

[英]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. 就像标题所解释的那样,在subscribe成员内部调用router对象时,它会变得不确定。

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. 提交表单时将调用sendLogin()方法。 every varibales from the form are good. 表格中的每个变量都很好。

The process reach the subscribe perfectly, but then this._router.navigate(['/dashboard']); 进程完美地达到了subscribe ,但是随后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. 您必须使用箭头功能保留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));
     }

To avoid arrow function, you can use bind to bound the this context. 为了避免使用箭头功能,可以使用bind绑定this上下文。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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