我有两个 angular 组件,它们彼此不相关 Component 1 和 Component 2 ,我已经定义了一个函数来调用组件 2 中的 get API,以便我可以在 Component 2 html 上显示 API 响应,但我想调用在我单击 Component 1 中的某个按钮后,此功能。我尝试了共享服务方法,但它不起作用
1> 这是我的共享服务:
private subject = new Subject<any>();
sendClickEvent(){
this.subject.next();
}
getClickEvent():Observable<any>{
return this.subject.asObservable();
}
2> 这是我与共享服务交互的 component1.ts 代码:
callMe(){
console.log("CALLLLLL MEEEEEEEEEEEEEEE")
this.shared.sendClickEvent();
console.log("CALLL MMMEEEE FINISHED")
}
## Here I am calling this CallMe() function in Component1 ##
<button class="btn btn-danger" (click)="callMe()" </button>
3> 这是我的 component2.ts 代码,我通过共享服务订阅 & FetchCustomer() 是我将通过 CallMe() 调用的 get API 函数:
clickEventSubscription : Subscription;
constructor(private http : HttpClient, private shared : SharedService) {
this.clickEventSubscription = this.shared.getClickEvent().subscribe(() => {
console.log("Click Event subscription")
this.FetchCustomer();
})
}