0

正如标题所解释的,当在成员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()提交表单时调用该方法。表格中的每个变量都很好。

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

例外:无法读取未定义的属性“导航”

有任何想法吗 ?

4

2 回答 2

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));
     }
于 2016-10-27T09:53:50.000 回答
0

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

// ...
this.authService.login(this.email, this.password)
  .subscribe(function(token){ //.. your code }.bind(this),
    error => console.log(error));
} // ...
于 2018-05-24T12:08:09.950 回答