Route to component and change some values of that component

I have two component in my Angular website, in my second component I have a function:

 this.ben = 1;

  send(){
    var param = JSON.stringify({'beneficiari': this.ben});
    console.log("JSON",param);
    this.http.post("", param).subscribe((res)=>{
    if (JSON.stringify(res as string)){
      console.log("RESP", res);
    }
    },(error)=>{
      console.log(error);
    }
  );
}

and in my first I have a button which should open the second component and execute the send() function changing "this.ben", how can I achieve this?

2 answers

  • answered 2019-10-15 17:41 Henrique Erzinger

    You should provably use a service for that send method, so you can inject it and call for either component. That way you can parametrize the route for your second component and get it from the ActiveRoute's ParamMap observable, and simply use a routerLink for your button. Also, you don't need any of those JSON.stringify with Angular's HttpClient.

  • answered 2019-10-15 17:46 Charly Sosa

    In your first component add

    @ViewChild(ChildComponent) child: ChildComponent;
    ...
    ngOnInit() { 
       this.child.send();
    }
    

    Regards