我想在角度项目的typescript类中引用关键字“this”。但不能用。我总是得到一个错误,我想改变的变量没有定义。以下是我的实现:

export class ContactComponent implements OnInit {
  contactForm: FormGroup;
  errorMsg:string = '';
  redirect = "";

  loggedIn(): void {
         this.redirect = "dashboard";
         console.log("success");

在我的HTML中,重定向变量连接到RouterLink,如下所示:
<a [routerLink]="redirect"></a>

我已经尝试过其他函数中的其他变量,但是总是有相同的错误。
编辑:
LoggEdIn函数在另一个函数中称为“成功”参数,如下所示:
submitForm(): void {
    DBEventProxy.instance().dbevent.login(this.contactForm['username'],
    this.contactForm['password'], this.loggedIn, this.failed);
  }

登录函数需要参数用户名、密码、成功函数、故障函数。

最佳答案

您需要将loggedIn绑定到正确的上下文。有几种选择:
1)定义loggedIn为绑定函数:

export class ContactComponent implements OnInit {
  loggedIn = () = > {
         this.redirect = "dashboard";
         console.log("success");`

2)使用bind
export class ContactComponent implements OnInit {
  contactForm: FormGroup;
  errorMsg:string = '';
  redirect = "";

  loggedIn(): void {
         this.redirect = "dashboard";
         console.log("success");

    submitForm(): void {
        DBEventProxy.instance().dbevent.login(this.contactForm['username'],
        this.contactForm['password'], this.loggedIn.bind(this), this.failed);
                                                    ^^^^^^^^^^
      }

3)将this.loggedIn包装成一个箭头函数,该函数保留如下上下文:
this.contactForm['password'], () => this.loggedIn(), this.failed);

可能您也希望对this.failed执行同样的操作。
阅读有关bind和箭头函数here的更多信息

07-28 07:42