“此"不能在打字稿功能(角度)中使用 [英] "this" cannot be used in typescript function (Angular)

查看:92
本文介绍了“此"不能在打字稿功能(角度)中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Angular项目的打字稿类中引用关键字"this".但是它不能被使用.我总是得到这样的错误:我想更改的变量未定义.这是我的实现:

I want to reference the keyword "this" in a typescript class in my Angular project. But it cannot be used. I always get the error that the variable I want to change is not defined. Here is my implementation:

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

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

在我的HTML中,重定向变量像这样连接到routerLink:

in my HTML the redirect variable is connected to a routerLink like this:

<a [routerLink]="redirect"></a>

我在其他函数中尝试了其他变量,但是总是有相同的错误.

I have tried this with other variables in other functions but had always the same error.

loginIn函数在另一个函数中被称为成功"参数,如下所示:

The loggedIn function is called within another function as "success" parameter like this:

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

登录功能需要参数用户名,密码,成功功能,失败功能.

The login function needs the parameters username, password, success function, failfunction.

推荐答案

您需要将loggedIn绑定到正确的上下文.有几种选择:

You need to bind loggedIn to the correct context. There are several options:

1)将loggedIn定义为绑定函数:

1) define loggedIn as bound function:

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包装到一个箭头函数中,该函数保留如下所示的上下文:

3) wrap this.loggedIn into an arrow function that preserves context like this:

this.contactForm['password'], () => this.loggedIn(), this.failed);

也许您想对this.failed做同样的事情. 在此处了解更多有关bind和箭头功能的信息.

And probably you want to do the same for this.failed. Read more about bind and arrow functions here

这篇关于“此"不能在打字稿功能(角度)中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆