ESLint 抱怨空构造函数和 ngOnInit 实现

Kon*_*ten 21 constructor eslint angular

在我的 Angular 应用程序中,规则no-empty-function触发了我的构造函数的错误。嗯,它确实是一个空的主体,但构造函数本身需要在那里,因为我注入了一个服务。

export class ClientListComponent implements OnInit {
  constructor(service: AuxService) { }
  ngOnInit() { }
  ...
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,它还抱怨接口的实现方法。然而,这两者之间的错误消息有所不同,这也让我感到困惑。

意外的空构造函数。
意外的空方法“ngOnInit”。

因此,它清楚地区分了普通方法(由于实现的接口,仍然需要一个方法,我认为这本身就是错误的)和构造函数。我确信创建者听说过依赖注入,所以我不明白我错过了什么。

Jas*_*lez 17

您还可以修改.eslintrc.json文件以从 linter 中排除该规则。

在此输入图像描述

  • "@angular-eslint/no-empty-lifecycle-method": 复制/粘贴时为“off” (7认同)
  • 这对我来说非常有效!对于像我这样的懒猫,我只留下代码片段:“@angular-eslint/no-empty-lifecycle-method”:“off” (3认同)

Wil*_*Hou 10

实际上存在多种规则的组合,而不仅仅是一个:

      "no-empty-function": "off",
      "@typescript-eslint/no-empty-function": "off",
      "@angular-eslint/no-empty-lifecycle-method": "off"
Run Code Online (Sandbox Code Playgroud)

仅在将上述三个规则添加到文件后,我才消除了所有空函数错误.eslintrc.json

复制这三个规则,将它们粘贴到您的.eslintrc.json文件中(在“规则”内),您将消除错误。

在此输入图像描述


小智 8

我认为您需要检查以下链接 https://eslint.org/docs/rules/no-empty-function

根据文档,以下错误是

    constructor() {}

    foo() {}
Run Code Online (Sandbox Code Playgroud)

这些是正确的

    constructor() {
        // do nothing.
    }

    foo() {
        // do nothing.
    }
Run Code Online (Sandbox Code Playgroud)


Ber*_*ove 6

您需要编辑.eslintrc.json文件并添加此行

"@angular-eslint/no-empty-lifecycle-method": "off"
Run Code Online (Sandbox Code Playgroud)

或者查看这个文件

{
    "root": true,
    "ignorePatterns": ["projects/**/*"],
    "overrides": [
        {
            "files": ["*.ts"],
            "parserOptions": {
                "project": ["tsconfig.json"],
                "createDefaultProgram": true
            },
            "extends": [
                "plugin:@angular-eslint/recommended",
                "plugin:@angular-eslint/template/process-inline-templates"
            ],
            "rules": {
                "@angular-eslint/directive-selector": [
                    "error",
                    {
                        "type": "attribute",
                        "prefix": "app",
                        "style": "camelCase"
                    }
                ],
                "@angular-eslint/component-selector": [
                    "error",
                    {
                        "type": "element",
                        "prefix": "app",
                        "style": "kebab-case"
                    }
                ],
                "@angular-eslint/no-empty-lifecycle-method": "off"
            }
        },
        {
            "files": ["*.html"],
            "extends": ["plugin:@angular-eslint/template/recommended"],
            "rules": {}
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)