如何在 Angular Class 中访问 'this' 上下文?

How to access 'this' context in Angular Class?

另一个 'context' 问题。

我有一个名为“isInDatabase()”的函数。它应该是一个自定义验证器,我在 'angular/validator' Github 页面上得到灵感。

如您所见,我正在调用“this.clientService.checkElement”函数。正如声明的那样,我收到错误消息:“无法读取未定义的 属性 'checkElement'”。

提示 1:(?)

根据我已经看到和阅读的内容,上下文已经改变,即使我使用箭头函数,因为这个箭头函数被另一个函数包裹。

提示 2:(?)

我试图实现这个:constructor (private clientService: ClientService) {},但随后,错误是:错误 TS2339:属性 'clientService' 在类型 [= 上不存在47=].

这是代码:

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);
    };
  }
}

您无法从静态方法访问 this,因为 this 引用了 this class 的实例,而您没有静态方法中没有实例。

这篇文章也是一本很好的读物,可以更好地理解 'this' in TypeScript