微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Typescript 从 Codemirror 调用 SQL linter 的 API

如何解决使用 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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。