使用 Typescript 从 Codemirror 调用 SQL linter 的 API

问题描述

我正在尝试调用一个 API 来 lint 用 Codemirror 编写的 sql 查询(实际上我使用 Angular 和包装器 ngx-codemirror)

很遗憾,我无法调用 API,因为这被认为是未定义的:

data-analyzer.component.html:81 ERROR TypeError: Cannot read property 'analyzerService' of undefined
    at testA (data-analyzer.component.ts:624)
    at lintAsync (lint.js:134)
    at startLinting (lint.js:152)
    at Object.lint (lint.js:248)
    at new CodeMirror (codemirror.js:7885)
    at CodeMirror (codemirror.js:7831)
    at Function.fromTextArea (codemirror.js:9682)
    at ctrl-ngx-codemirror.js:64
    at ZoneDelegate.invoke (zone-evergreen.js:365)
    at Zone.run (zone-evergreen.js:124)

我的代码如下:

<ngx-codemirror
    #ref
    name="query"
    [options]="config"
    [(ngModel)]="item.query"
    (keypress)="CMonKeyPress($event)"   
>
</ngx-codemirror>
config = {
    mode: 'text/x-MysqL',showHint: true,lint: {
        lintOnChange: true,getAnnotations: this.lintsql
    },gutters: [
        'CodeMirror-linenumbers','CodeMirror-lint-markers'
    ]
};

constructor(
    private analyzerService: DataAnalyzerService
) {}

lintsql(a: string,b: LintStateOptions,cm: Editor) {
    const found: Annotation[] = [];

    // The error occurs here
    this.analyzerService.lint(this.item.query).subscribe(
        (r: any) => {
            console.log(r.data);  
        },(err) => {
            console.log(err);
        }
    );

    // So far I return an empty array,the focus is to get the results from the service
    return found;
}

I would like to kNow how Could I access to the service in the linting function.

解决方法

this question找到,解决方法是绑定(this)如下:

getAnnotations: this.lintSQL.bind(this)