I've 2 components in my app. On click of a button in one component, I want to call a function in other component. The function takes an id as an argument and needs an object. I am able to send either the id or object from first component using RXJS but not both at the same time. Both these components are siblings. Here is what my code looks like.
COMPONENT 1:-
searchObject;
toggle1(id:number){
this.dashboardService.sendToggleEvent(id);
}
SERVICE:-
sendToggleEvent(id:number){
this.toggleSubject.next(id);
}
getToggleEvent():Observable<any>{
return this.toggleSubject.asObservable();
}
COMPONENT 2:-
constructor(){
this.toggleEventSubscription =
this.dashboardService.getToggleEvent().subscribe((id)=>{
this.toggle2(id);
});
}
toggle2(id){
if(id == __){
api(searchObj)
}
toggle2 has an api that needs an object called searchObj which is in Component 1. I'm calling toggle2 whenever toggle1 is called and passing the id but not able to pass the searchObject.
TIA.
CodePudding user response:
You will need a service for that and property of type subject
service.ts
mySub = new Subject();
componet1
this.myService.mySub.next({id:123,data:{}})
component2
this.myService.mySub.subScribe(event=>{
this.callfn(event.id,event.data)
})
CodePudding user response:
Without code it will be difficult to help you but I will try.
So you are using RXJS and I mean observable. So when your second component receive the id or object, you can call the function (inside the subscribe).
observable.subscribe({
next(x) { callFunction(x) },
error(err) { console.error('something wrong occurred: ' err); },
complete() { console.log('done'); }
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Do not hesitate to take a look on the documentation : https://rxjs.dev/guide/observable