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

后端 未结 3 509
逝去的感伤
逝去的感伤 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:32

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

    1) define loggedIn as bound function:

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

    2) use 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) wrap this.loggedIn into an arrow function that preserves context like this:

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

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

提交回复
热议问题