Reputation: 6242
I have a button that opens popup where user selects some data and add to my form.
<button type="button" class="btn btn-info btn-sm" aria-hidden="true" (click)="addData()"> Add Data</button>
addData() {
this.bsModalRef = this.modalService.show(PopupComponent,
{ initialState: { createForm: this.createForm }, ignoreBackdropClick: true, animated: true, keyboard: true, class: '' });
//some code to save below
//this.bsModalRef.content.onSave
}
The above opens a pop, user selects some data and press save.
In my popup component I have this:
ngOnInit() {
this.myService.getData().subscribe((data: any[]) => {
this.myList = data.map(a => [{ name: a.name }][0]);
},
(error: any) => {
console.log(error);
});
}
I then bind myList to my select in my popup component html All of the above works fine.
The issue is when the user clicks Add Data it, it open the popup and calls my service again.
Is it possible to avoid the multiple service calls whenever user clicks add again and again.
I tried setting the value of data returned from the api to a variable which gets assigned but on the button click its always empty.
Any input please.
Upvotes: 0
Views: 3061
Reputation: 812
Each time you open the modal, it is initialized from scratch. Since you have the service call on the ngOnInit
of the modal, it will called each time.
You can possibly change the logic to call myService.getData
from the main component and then pass this to the modal for each click of Add Data button.
Modify your main component to call myService
and store the result in myList
during initialisation. Also, modify your addData()
method to pass this value with the initialState
to the modal.
ngOnInit(){
this.myService.getData().subscribe((data: any[]) => {
this.myList = data.map(a => [{ name: a.name }][0]);
},
(error: any) => {
console.log(error);
});
}
addData() {
this.bsModalRef = this.modalService.show(PopupComponent,
{ initialState: { createForm: this.createForm, myList: this.myList }, ignoreBackdropClick: true, animated: true, keyboard: true, class: '' });
}
Now, myList
in your modal will already have the required data passed from the main component and the network call can be removed from ngOnInit
of the modal.
Upvotes: 1
Reputation: 557
You probably can retrieve the data of myList
in the form component and then pass it as data in the Dialog
.
Upvotes: 0