“this” cannot be used in typescript function (Angular)

后端 未结 3 496
逝去的感伤
逝去的感伤 2020-12-12 02:01

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

3条回答
  •  粉色の甜心
    2020-12-12 02:28

    Since you're using Typescript, you can use arrow functions to preserve the context you expect (this will refer to what you want).

    In SubmitForm(), replace this.loggedIn with ()=>this.loggedIn(). The same change should be made to this.failed if that's a function.

    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.

提交回复
热议问题