IntelliJ 错误地建议在 Angular 应用程序中将方法设为静态

dis*_*ame 3 intellij-idea typescript angular

我有一个简单的注册组件,它除了将表单提交到涅槃之外什么也不做。然而,IntelliJ 认为这onSubmit可能是static。如果我将签名更改为,static我无法调用该方法 - 至少据我所知 - 所有答案都表明无法从模板内调用静态组件方法。

显然 IntelliJ 没有意识到我实际上是在模板中调用这个方法,因此错误地建议创建该方法static

有没有解决方法,或者我只能忍受这个警告?

这是一个例子:

成分:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  data: any;
  constructor() {
    this.data = {
      username: ''
    };
  }

  // WARNING: Method can be static
  onSubmit(event) {
    alert('Submitting ..');
  }

  ngOnInit() {
  }

}
Run Code Online (Sandbox Code Playgroud)

模板:

<form (ngSubmit)="onSubmit($event)">    
  <mat-grid-list cols=1>

    <mat-form-field>
      <input matInput placeholder="Username" [(ngModel)]="data.username" name="uname">
    </mat-form-field>    
    <mat-grid-list cols=2>
      <button mat-button type="submit">Ok</button>
      <button mat-button>Cancel</button>
    </mat-grid-list>

  </mat-grid-list>    
</form>
Run Code Online (Sandbox Code Playgroud)

jep*_*bio 5

Intellij 建议将此类方法设为静态,因为它们不会触及实例的任何状态。

您可以将 onSubmit 方法设为静态:

static onSubmit(event) {
    alert('Submitting ..');
}
Run Code Online (Sandbox Code Playgroud)

然后 intellij 会警告您将此方法放在类的非静态方法之前。

然后,您需要在组件中提供一个 getter,以便像您一样从模板中调用静态成员。

onSubmit = RegisterComponent.onSubmit;
Run Code Online (Sandbox Code Playgroud)

所以,你的代码应该是:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  data: any;

  onSubmit = RegisterComponent.onSubmit;

  static onSubmit(event) {
    alert('Submitting ..');
  }

  constructor() {
    this.data = {
      username: ''
    };
  }

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

这将会起作用,并且您不会收到任何警告。

  • 这看起来有点荒谬——你基本上只是添加额外的代码来让 IDE 满意(因为它试图做正确的事情,但没有正确理解 Angular 框架)。为什么不直接取消对该线路的检查呢?或者甚至完全禁用它,对于 Angular 项目来说,它可能会造成比其价值更多的麻烦...... (3认同)
  • “因为它们不触及实例的任何状态”。我认为这就是确切的原因,并且解释得很好。 (2认同)