I have a parent component with route /home which contains a list and when a list item is clicked, I navigate to /home/edit/listid and update the database. After the database update, I am navigating back to /home. But the list is not updated until I refresh the page manually. I also tried calling dataservice.getList() after updating the database, but no luck. Below is my code. Can someone please help me identify what I am missing?
Home Component
ngOnInit() {
this.loadList();
}
loadList() {
this.dataservice.getList().subscribe(
res => {
this.List= res;
},
err => {
console.log('Error Occoured');
console.log(err);
}
);
}
DataService getList()
getList(): Observable<any[]> {
return this.http.post<any[]>('https://resturl/Prod/getdata', {
'operation': 'getData'
}
});
}
Edit List
this.dataservice.updateList().subscribe(
updateAccRes => {
this.dataservice.getList();
this.router.navigate(['/home']);
}
},
error2 => {
console.log(error2);
}
);
JavaScript's asyn is your problem. When you navigate to Home, the response of updated list has not came back yet, so you have to manually reload the page. A solution for this is to have a common variable in service which can be accessed by both components and *ngIf in your Home Component's HTML to check for updates in the common variable.
Edit List You just need to update items here. The navigation should be called inside this.dataservice.getList() to make sure it wait for the response from the getList() call.
this.dataservice.updateList().subscribe(
updateAccRes => {
this.dataservice.getList();
}
},
error2 => {
console.log(error2);
}
);
DataService getList() Create a common variable here, update it with the response from getList(), and then navigate to /home
latestList: any;
getList(): Observable<any[]> {
return this.http.post<any[]>('https://resturl/Prod/getdata',
{'operation': 'getData'})
.subscribe(response => {
this.latestList = response.list;
this.router.navigate(['/home']);
},
error => {
console.log(error);
}
)};
Home Component Now, after updated list comes back, we are navigated to home page, and the updated list is ready to be displayed without manually reload the page.
listOfItems: any
constructure(private dataService : DataService){
// latestList is accessible here because it is a property of DataService
this.listOfItems = this.dataService.latestList;
};
home.component.html You can check for the updated list's existence here. If it exists, show it. If it does not exist, show "loading...." message.
<div class="list" *ngIf="listOfItems"> <!-- Display list here --> </div>
<div *ngIf="!listOfItems"> Loading.......... </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With