首页 > 解决方案 > 如何在Angular 8中调用另一个组件的方法

问题描述

在此处输入图像描述

我已经在 Image 中解释了这个场景。

我有一个LayoutComponent
其中有 1) LeftMenuComponent和 2) Router-OutletLeftMenuComponent我有LoyaltyComponent,它来自Shared Folder

我想从 RouterOutlet 中的任何组件调用 LoyaltyComponent ngOnInit 方法。

请注意:LoyaltyComponent 在共享文件夹内,而 OrderListComponent 在订单文件夹内。

有什么方法可以调用跨组件方法,或者我只需要从 OrderList 组件中刷新 LoyaltyComponent。

我试过了:

@ViewChild('Loyalty') private loyaltyComponenet : Loyalty;

但它给了我不确定的。

Also from using behaviourSubject, can I directly call ngOnInit of LoyaltyComponent?

忠诚度组件.ts

export class Loyalty implements OnInit {

    public loyaltyMet: number;
    public loyaltyThreshold: number;
    public loyaltyBarWidth: number;
    public loyaltyRequired : number;
    constructor() {
    }

    public ngOnInit(): void {     
        this.loyaltyMet = Context.loyaltyMet;
        this.loyaltyThreshold = Context.loyaltyThreshold;
        this.loyaltyRequired = this.loyaltyThreshold - this.loyaltyMet;
        this.loyaltyBarWidth = this.loyaltyMet * 100 / this.loyaltyThreshold;

        if (this.loyaltyRequired < 0) {
            this.loyaltyRequired = 0;
            this.loyaltyBarWidth = 100;
        }
    }
}

标签: angularangular7

解决方案


我相信Context是通过构造函数注入的,那是服务吗?

您可以在该服务上有一个方法说“刷新”或其他东西,当触发时,它会通过一个简单的主题发出一个值。

您的忠诚度组件,可以在初始化时订阅该主题,并在其触发时对其做出反应。

只要该Context服务被用作所有消费者的单例(如,提供一次),您就可以开始使用了。


推荐阅读