【问题标题】:Creating shared methods in Angular在 Angular 中创建共享方法
【发布时间】:2020-06-02 23:51:21
【问题描述】:

我想创建一些方法并从不同组件的 html 中调用它们。另一方面,How to call static method of other class in .html (not in .ts)? 有一些方法,但它很旧,我想知道 Angular 9 中是否有更好的方法来直接调用该方法。也可以使用共享服务并在该服务中定义共享方法,但我正在寻找另一种直接从 html 调用静态方法的方法。我该怎么做?

demoBase.ts:

export class DemoBase {
    static demoMethod(id) {
        //
    }
}

那我想从另一个组件的html调用这个方法:

list.component.ts:

import { DemoBase } from '@pages/demoBase';

//other stuff (I do not want to create a method here to access base method)

list.component.html:

<div><span [ngClass]="DemoBase.demoMethod(record.Id)">{{record.Name}}</span></div>

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    我相信 Angular 中的 services 是您正在寻找的东西?

    它们也与它们的数据和方法共享。它们可以在模块级别共享。

    详情请看article

    【讨论】:

    • 感谢您的回复,我在我的项目中使用了这种方法。但是我的问题中的情况有点不同,这些方法就像一个计算器,不会从服务器获取数据,因此我想为这些方法创建一个新的单独类。另一方面,即使在服务方法中,我也不想在组件中再次创建相同的方法。
    • 所以,我认为最好的办法是在 How to call static method of other class in .html (not in .ts)? 上使用 @CalebMacdonaldBlack 的解决方案。不是吗?
    • 即使它们不从服务器获取数据,服务也可以服务于共享方法和数据的目的。此外,无论您使用哪种方法,您都需要在某处(在 .ts 中)声明该类的实例,否则 HTML 将不知道实例变量。看这个可能是:stackoverflow.com/questions/41857047/…
    • 我上面提到的页面上的方法似乎更干净,因为它使用scoreboardInstance = ScoreBoard.getInstance(); 而不是方法声明。这是真的吗?
    • @Manish 这是完全不相关的答案。 Clint Eastwood 不要求组件之间共享数据。
    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 2018-10-26
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多