Reputation: 191
this is my first question here, sorry if it's not well structured.
I have a parent component, component1, that has a form,
and it calls component2, which also has a form.
Component2 has its own database collection, but it only can be saved if parent component were too. So it has an Input property called write
, that component1 set to true when user click on save button.
This Input is been checked with OnChanges, by component2.
NgOnChanges call writeOnDB()
, and this is working fine.
writeOnDB try to persists the component2 form data, and emit an Output saved
, with true on success, or false on fail.
So, component2 is being called like this:
<component2
[write]="saveForm"
(saved)="onCmp2Saved($event)">
</component2>
My submit function is like this:
onSubmit(form) {
// Get form values and save into component1 object
this.cmp1 = form;
// Set Flag to save component2 on BD
this.saveForm = true;
let result = this._cmp1Service.editData(this.cmp1)
//TODO: Check if component2 successfully saved its form before proceed
result.subscribe(
res => _router.navigate['home'],
error => ...
);
}
So the question is,
how do I wait for the component2 emit saved
output?
I always find my answers here, but I think I'm not knowing how to search this, cause I didn't find anything.
Thanks!
Upvotes: 0
Views: 245
Reputation: 364697
It looks like you need to wait for two things to happen before you continue:
saved
event from component2editData()
Since you don't know which will finish first, you'll need each handler to check to see if the other completed. Something like:
onSubmit(form) {
this.cmp1 = form;
this.saveForm = true;
this.component2Done = false;
this.component1Done = false;
this._cmp1Service.editData(this.cmp1).subscribe(
res => {
this.component1Done = true;
if(this.component2Done) { doSomething(); }
},
error => ...
);
}
onCmp2Saved(result) {
this.component2Done = true;
if(this.component1Done) { doSomething(); }
}
Upvotes: 1