"this" 不能在 typescript 函数中使用 (Angular)

"this" cannot be used in typescript function (Angular)

我想在我的 Angular 项目的打字稿 class 中引用关键字 "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 函数在另一个函数中作为 "success" 参数调用,如下所示:

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

您需要将 this 绑定到它,而不仅仅是引用该函数:this.loggedIn.bind(this).
仅引用函数时将其从引用时的 this 引用中“剥离”。这是标准的 Javascript 行为。

由于您使用的是 Typescript,因此您可以使用箭头函数来保留您期望的上下文(this 将引用您想要的内容)。

SubmitForm() 中,将 this.loggedIn 替换为 ()=>this.loggedIn()。如果这是一个函数,则应对 this.failed 进行相同的更改。

DBEventProxy.instance().dbevent.login(
    this.contactForm['username'], 
    this.contactForm['password'], 
    ()=>this.loggedIn(), 
    ()=>this.failed()
);

See the Typescript wiki

Red flags for this

The biggest red flag you can keep in mind is the use of a class method without immediately invoking it. Any time you see a class method being referenced without being invoked as part of that same expression, this might be incorrect.