1

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);
    };
  }
}
1
  • So, if some people are interested: I have changed my static methods to non-static methods. That way, I need to instantiate an object of this class if I want to call my functions. So it works, but at that point, I still need to know what is the best usage of static methods and why we do use static methods. (if someone has the answer btw) Commented Jan 1, 2019 at 1:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oooow! Seems logical! Even if I seem to definitey read this article... Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.