Issue
I´m switching from using Promises to Observables and have a problem understanding how to subscribe to modal values, this is my current code. I marked HERE in the second example, where the value stays undefined.
Modal TS:
onEditSave(): void {
if (this.formGroup.invalid) {
console.error('Invalid form-data: ', this.formGroup);
return;
}
const item: ItemDto = {
_id: this.currentItem._id,
item_id: this.formGroup.get('new_item_id').value,
item_description: this.formGroup.get('new_item_description').value,
[...]
item_time: this.formGroup.get('new_item_time').value,
item_arrival: this.formGroup.get('new_item_arrival').value
};
this.dialogRef.close(item);
}
Component TS:
openEditDialog(item: ItemDto): void {
const dialogRef = this.editDialog.open<EditComponent, ItemDto, ItemDto>(EditComponent, {
data: {
_id: item._id,
item_id: item.item_id,
item_description: item.item_description,
[...]
item_time: item.item_time,
item_arrival: item.item_arrival
}
});
// Here
dialogRef.afterClosed().subscribe(data => { this.editResult = data });
if (!!this.editResult) {
try {
this.itemsService.updateItem(this.editResult);
} catch (error) {
console.error('Error: ', error);
}
}
}
Solution
What is in the subscribe is an asynchronous operation, and in your example it will be executed later than the check in the if. So you need to move if-statement inside:
dialogRef.afterClosed().subscribe(data => {
this.editResult = data;
if (!!this.editResult) {
try {
this.itemsService.updateItem(this.editResult);
} catch (error) {
console.error('Error: ', error);
}
}
});
Answered By - Eugene
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.