angular - 如何在Angular 8中调用另一个组件的方法
问题描述
我已经在 Image 中解释了这个场景。
我有一个LayoutComponent,
其中有 1) LeftMenuComponent和 2) Router-Outlet
在LeftMenuComponent我有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;
}
}
}
解决方案
我相信Context
是通过构造函数注入的,那是服务吗?
您可以在该服务上有一个方法说“刷新”或其他东西,当触发时,它会通过一个简单的主题发出一个值。
您的忠诚度组件,可以在初始化时订阅该主题,并在其触发时对其做出反应。
只要该Context
服务被用作所有消费者的单例(如,提供一次),您就可以开始使用了。
推荐阅读
- android - 编辑正在运行的应用程序中存在的共享首选项条目
- wordpress - 在没有 CDN 的 Wordpress 插件中包含 Vue.js 组件
- batch-file - 从批处理启动应用程序会杀死整个 Windows 脚本
- python - Python中的正则表达式:无法匹配重复的组号
- c# - Asp.Net Core PageStart.cshtml 替代方案?
- javascript - “HTMLElement”类型上不存在属性“值”
- python - 为什么不显示 ValueError
- php - 为什么在没有点击 ajax 提交/验证功能的情况下进行提交
- google-app-engine - 从 Cloud Tasks 启动时,Node App Engine 任务已超过截止日期
- c++ - 为类提供模板如何解决无效的 constexpr 依赖项?C++