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

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

本文介绍了angular2路由器在subscribe方法中变为未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所解释的那样,当在subscribe成员内部调用router对象时,该对象将变得不确定.

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

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

the method sendLogin()is called when submitting a form.every varibales from the form are good.

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

The process reach the subscribe perfectly, but thenthis._router.navigate(['/dashboard']); gives me :

有什么想法吗?

推荐答案

您必须使用箭头功能来保留this上下文.

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

这篇关于angular2路由器在subscribe方法中变为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 21:19