繁体   English   中英

如何在Angular 8中调用另一个组件的方法

[英]How to call method of another component in Angular 8

在此处输入图片说明

我已经解释了Image中的场景。

我有一个LayoutComponent
在其中,我有1) LeftMenuComponent和2) 路由器插座LeftMenuComponent旁边,我有LoyaltyComponent ,它来自Shared Folder

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

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

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

我试过了:

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

但这给了我不确定的信息。

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

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;
        }
    }
}

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

您可以在该服务上使用一个方法,说“刷新”或类似的内容,该方法在触发时会通过一个简单的主题发出一个值。

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

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

如果组件是父级和子级,则使用@Input@Output ,如果不是,则使用EventEmitter这是解决方案https://stackoverflow.com/a/57324581/2762191

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM