简体   繁体   中英

How do I pass an id and object on click of a button from one component to another component' s function in angular?

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.

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

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

Do not hesitate to take a look on the documentation : https://rxjs.dev/guide/observable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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