【问题标题】:How to access declared variable from app.component to other components?如何从 app.component 访问声明的变量到其他组件?
【发布时间】:2016-10-20 23:42:28
【问题描述】:

我是 Typescript 和 Angular 2 的新手。我试图在网上寻找答案,但它们似乎不适合我。

假设我有一个 app.component 如下所示:

export class AppComponent{
    cartPayableAmount = 0;

    ........
}

in my app.component.html, the cartPayableAmount is used here

<div> {{cartPayableAmount}} </div>

现在我想访问其他类中的 cartPayableAmount 实体,如下所示:因此,当我调用 TestHere() 时,cartPayableAmount 的值将发生变化,并将反映在 app.component.html 中。

export class BuyTestComponent {
    TestHere() {
        // should update cart PayableAmount here.....
        cartPayableAmount  = "Some value"
    }
}

请帮忙。谢谢

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以创建一个新服务,可能称为ShoppingCart,它包含该值。然后可以将其注入到您的组件中。

    但在您的示例中,cartPayableAmount 是一个计算值,因此您希望它是计算它的方法或 Observable,而不是类属性。

    【讨论】:

    • 我实际上在 app.component 中有一个方法,用于计算 cartPayableAmount。但该方法仅在 app.component 内部使用。我还没有尝试过 Observable 实现。我会尝试一下。谢谢
    • 即使该方法仅在一个地方使用,您也应该将所有购物车逻辑整合到一项服务中。
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2021-11-17
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多