【问题标题】:Static functions in Angular-templateAngular-template 中的静态函数
【发布时间】:2021-06-10 15:38:24
【问题描述】:

在我们的项目中,我们使用来自AirBnB 的 linting-config。 The is a rule,表示类方法必须使用 this 或声明为静态。从理论上讲,这条规则对我来说很有意义,但在角度上下文中似乎会引起一些问题。想象一下这样的组件 (Stackblitz):

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

@Component({
  selector: 'my-app',
  template: '<p>{{doSomething("hello stack overflow")}}'
})
export class AppComponent  {
  doSomething(string: string): string {
    return string.toLocaleUpperCase();
  }
}

现在,linter 会抱怨 doSomething 没有使用它。 Wen 现在可以将函数设为静态来满足它 - 但我们将无法在模板中使用该函数。

一个结论是,doSomething 不应该是 AppComponent 的一部分,而是另一个服务。但是,我们将不得不再次将静态函数包装在非静态函数中。最后包装的功能比原来的小不了多少,所以整个外包到服务的事情似乎有点毫无意义。特别是因为我们谈到了明确只对组件模板有用的函数。这似乎是有问题的,尤其是对于ngForOf 的trackBy 的跟踪功能-它们本质上往往不使用this 关键字,并且仅在模板中使用,因此它们不能是静态的。

那么是否有一个有意义的模式来处理模板中使用的函数以及这个规则,或者它只是不是一个有用的角度规则?

【问题讨论】:

  • 我想说您可以使用 Angular 管道 (angular.io/guide/pipes) 来实现这些模板数据转换功能。事实上,你也可以在 trackBy 中使用它们 (bennadel.com/blog/…)。但是随后 linter 会抱怨管道。因此,由于管道是 Angular 的重要组成部分,我会说它可能不适合 Angular 的规则(除非您可以从中排除管道)

标签: javascript angular typescript


【解决方案1】:

我自己找到了一个令人满意的解决方案:

我转换了那些功能 - 小的,与 UI 相关的,(仅)在模板中使用,不使用范围 (this) 作为字段,持有箭头函数。

  doSomething = (string: string): string => string.toLocaleUpperCase();

【讨论】:

    【解决方案2】:

    您还可以在 .ts 中定义外部函数,例如:

    export function myFunction(name){
       return "Hello "+name;
    }
    

    你只需要一个组件

    import {myFunction} from './myfile.ts' 
    

    那么就可以在.ts中使用了

       myFunction("Me");
    

    如果你想在 html 中使用,你需要在你的 .ts 中声明

      myFunctionI=myFunction;
    

    并使用

      {{myFunctionI('me')}}
    

    其他选项:您的 .ts 喜欢

    export function Util() {
        return new UtilClass()
    }
    class UtilClass {
       greet(name){
           return "Hello "+name;
       }
    }
    

    你可以

    import {Util} from './myfile-util.ts' 
    
    console.log(Util.greet("me"))
    

    【讨论】:

    • 但是为了在模板中使用它们(组件的html-部分),我必须将它们包装在组件的一些成员函数中。
    • @Paflow,在 html 中所有的“变量”都被称为“this”。例如您可以不在 .html {{Math.round(3.2)}} 中使用 directlty。但是你可以在你的组件中声明IMath=Math 然后你使用{{IMath.round(3.2)}} -我喜欢在“变量”之前添加一个“I”,但这只是一个个人选项。等于您要使用的另一个“函数”或类。
    【解决方案3】:

    对于你的情况,我认为管道更好。

    【讨论】:

      猜你喜欢
      • 2014-06-09
      • 2021-10-20
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多