Miran Parkar
Miran Parkar

Reputation: 1583

How to update values in component after post request from ngx-modal

I have Clints modal component which post data to backend and returns back new Clients

submitForm() {

const body = this.clients;

return this.http.post('api/clients', body).subscribe(data => {

});

}

I have another compnent named ClientsCompnent which has all clients details

ngOnInit() {

if (window.screen.width === 425) { // 425px portrait
  this.gbSearch = true;
}

this.http.get('/api/clients').subscribe(data => {
  this.clients = data;
});
}

So how do i updated the clients variable in clientsComponent with the data i get back from post method in clients modal component

Upvotes: 0

Views: 201

Answers (2)

Nour
Nour

Reputation: 5889

If i understand you well, you need to pass an event from the clients modal to the client component.

Okay i think there is more than one way to solve it:

  1. If the modal component is child of the clients component, so you should use @output like below:

In the modal component:

 private @Output() updateClients = new EventEmitter();
 submitForm() {

   const body = this.clients;

   return this.http.post('api/clients', body).subscribe(data => {
      this.updateClients.emit(data);
   });
 }

And in the clients component html:

<clients-modal (updateClients)="onUpdateClients($event)"></clients-modal>

Clients component ts:

private getClients(){
  this.http.get('/api/clients').subscribe(data => {
     this.clients = data;
  });
}

private onUpdateClients(data:any){
    this.getClients();
}
  1. If there is no parent child relationship, you should use the sharedService please read follow the link below:

http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41437

wrap the get request inside a function and call it inside both onInit and submit function

submitForm() {

    const body = this.clients;

    return this.http.post('api/clients', body).subscribe(data => {
        // if success call this 
        this.getClient();
    });
}


ngOnInit() {

    if (window.screen.width === 425) { // 425px portrait
        this.gbSearch = true;
    }
    this.getClient();

}

getClient() {
    this.http.get('/api/clients').subscribe(data => {
        this.clients = data;
    });
}

Upvotes: 0

Related Questions