【问题标题】:"this" cannot be used in typescript function (Angular)“this”不能用于打字稿功能(Angular)
【发布时间】:2017-11-28 02:22:26
【问题描述】:

我想在我的 Angular 项目的打字稿类中引用关键字“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方法?
  • 编辑了我的问题,总是忘记一些必要的信息

标签: angular typescript this angular2-routing


【解决方案1】:

您需要将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

【讨论】:

  • @Boerne,对,谢谢)您是否尝试过第一个选项loggedIn = () = &gt; {
【解决方案2】:

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

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

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

See the Typescript wiki

this 的危险信号

您可以记住的最大危险信号是使用类方法而不立即调用它。任何时候你看到一个类方法被引用而不被作为同一表达式的一部分调用,这可能是不正确的。

【讨论】:

  • 这不是我项目的正确解决方案。当我将 this.loggedIn 更改为 this.loggedIn() 时,主函数 dbevent.login() 无法正常工作。无法读取传入的 JSON 消息,并且无法登录。绑定函数工作正常!
  • this.loggedIn只是作为主函数成功参数的函数引用。如果我写 this.loggedIn() 函数将立即执行,这不是我想要的。
  • 你误读了我的回答。我没有要求你替换为this.loggedIn()。我写了()=&gt;this.loggedIn()
  • @Boerne,您在使用.bind 时遇到了什么错误?我想了解为什么bind 不起作用。实际上bind通过apply返回了内部调用this.loggedIn的新函数,这和()=&gt;this.loggedIn()做的差不多
  • @Maximus 您的解决方案中没有错误。但是,如果更改“正确”答案是不礼貌的,我很抱歉。但是所有给出的答案都是正确的,所以我认为最好标记最优雅的答案(我的观点)。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-10-04
    • 2014-04-05
    • 2019-01-21
    • 2016-09-27
    • 2020-04-25
    相关资源
    最近更新 更多