首页 > 解决方案 > 使用 Typescript 从 Codemirror 调用 SQL linter 的 API

问题描述

我正在尝试调用 API 来检查用 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.

标签: sqlangulartypescriptcodemirrorngx-codemirror

解决方案


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

getAnnotations: this.lintSQL.bind(this)

推荐阅读