You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中ngx-codemirror的SQL lint回调访问服务报undefined如何解决

问题原因

报错是因为 getAnnotations 回调函数执行时的this指向发生了变更,不再指向当前Angular组件实例,而是指向了CodeMirror的lint配置对象,所以无法访问注入的analyzerService。

解决方案

方案1:用箭头函数定义lint方法

箭头函数不会创建自己的this,会继承外层作用域的this,直接修改lintSQL的定义方式即可:

// 把原来的函数定义改成箭头函数
lintSQL = (a: string, b: LintStateOptions, cm: Editor) => {
    const found: Annotation[] = [];
    this.analyzerService.lint(this.item.query).subscribe(
        (r: any) => {
            console.log(r.data);
        },
        (err) => {
            console.log(err);
        }
    );
    return found;
}

方案2:在配置处用bind绑定组件实例

在给getAnnotations赋值时,手动把函数的this绑定为当前组件实例:

config = {
    mode: 'text/x-mysql',
    showHint: true,
    lint: {
        lintOnChange: true,
        getAnnotations: this.lintSQL.bind(this) // 此处绑定组件实例this
    },
    gutters: [
        'CodeMirror-linenumbers',
        'CodeMirror-lint-markers'
    ]
};

注意事项

你当前的lint方法是异步调用服务返回检查结果,但getAnnotations要求同步返回检查结果数组,直接返回空数组会导致lint错误标记无法正常展示。你可以拿到服务返回的错误列表后,手动调用CodeMirror实例的lint触发方法更新标记,即可正常展示错误提示。

内容的提问来源于stack exchange,提问作者Pierre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 10:27:02