Yves-Marie Ip
Yves-Marie Ip

Reputation: 84

How to access 'this' context in Angular Class?

Another 'context' problem.

I have this very function called 'isInDatabase()'. It is supposed to be a custom validator, I got inspiration on 'angular/validator' Github page.

As you can see I'm calling the 'this.clientService.checkElement' function. And as it is declared, I get the error: 'Cannot read property 'checkElement' of undefined'.

Hint 1: (?)

According to what I have already seen and read, the context has changed, even if I use an arrow function, because this arrow function is wrapped in another function.

Hint 2: (?)

I have tried to implement this : constructor (private clientService: ClientService) {}, but then, the error was : error TS2339: Property 'clientService' does not exist on type 'typeof CustomValidators'.

Here is the code :

export class CustomValidators {

    private static clientService: ClientService;

  static isInDatabase(elementType: string): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      this.clientService.checkElement(control.value, elementType)
        .subscribe(() => {
            return {isInDB: true};
          },
          (error) => {
            return {isInDB: true};
          });
      return (null);
    };
  }
}

Upvotes: 1

Views: 1031

Answers (1)

splash
splash

Reputation: 13327

You can't access this from a static method, because this references the instance of this class and you don't have an instance in a static method.

This article is also a nice read to better understand 'this' in TypeScript.

Upvotes: 1

Related Questions