Angular & Eslint - this.router.navigate(['/']) 的无浮动承诺错误

Angular & Eslint - no-floating-promises error with this.router.navigate(['/'])

我遇到以下 eslint 错误:

Promises must be handled appropriately or explicitly marked as ignored with the void operator.eslint@typescript-eslint/no-floating-promises

使用此代码:

this.router.navigate(['/']);

路由器是这样导入的:import { Router } from '@angular/router'; 并在 class.

的构造函数中赋值

我的 eslint 配置:

module.exports = {
  extends: [
    "plugin:@angular-eslint/recommended",
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:@typescript-eslint/recommended-requiring-type-checking",
    // "plugin:@angular-eslint/template/process-inline-templates",
    'prettier',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.eslint.json',
    sourceType: 'module',
    ecmaVersion: 2020,
  },
  plugins: ['@typescript-eslint', '@angular-eslint', 'prettier'],
  rules: {
    "prettier/prettier": [
      "error",
      {
        "printWidth": 140,
        "singleQuote": true,
        "useTabs": false,
        "tabWidth": 2,
        "semi": true,
        "bracketSpacing": true,
        "endOfLine": "lf"
      },
    ],
  },
};

是我的配置有问题还是有什么问题?我觉得 router.navigate 不应该是 angular 项目中的 eslint 错误。

我在 eslint 配置中添加了 '@typescript-eslint/no-floating-promises': 'warn' 规则。

规则 #no-floating-promises 说:

This rule forbids usage of Promise-like values in statements without handling their errors appropriately

所以这里你没有适当地处理 this.router.navigate 因为它 return 是 Promise

您可以:

  1. 等到return

    await this.router.navigate(['/']);
    
  2. 明确标记为有意不等待

    void this.router.navigate(['/']);
    
  3. 禁用此特定行的规则

    // eslint-disable-next-line @typescript-eslint/no-floating-promises
    this.router.navigate(['/']);