在Angular 5中更新数据库后刷新组件
发布时间:2020-12-17 18:11:05 所属栏目:安全 来源:网络整理
导读:我有一个包含路由/ home的父组件,其中包含一个列表,当单击列表项时,我导航到/ home / edit / listid并更新数据库.数据库更新后,我将导航回/ home.但是在我手动刷新页面之前,列表不会更新. 我也尝试在更新数据库后调用dataservice.getList(),但没有运气. 以下
我有一个包含路由/ home的父组件,其中包含一个列表,当单击列表项时,我导航到/ home / edit / listid并更新数据库.数据库更新后,我将导航回/ home.但是在我手动刷新页面之前,列表不会更新.
我也尝试在更新数据库后调用dataservice.getList(),但没有运气. 以下是我的代码.有人可以帮我识别我错过的东西吗? 家庭组件 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' } }); } 编辑列表 this.dataservice.updateList().subscribe( updateAccRes => { this.dataservice.getList(); this.router.navigate(['/home']); } },error2 => { console.log(error2); } ); 解决方法
JavaScript的asyn是你的问题.当您导航到主页时,更新列表的响应尚未返回,因此您必须手动重新加载页面.对此的解决方案是在服务中使用一个公共变量,可以通过主组件的HTML中的两个组件和* ngIf访问它以检查公共变量中的更新.
编辑列表 this.dataservice.updateList().subscribe( updateAccRes => { this.dataservice.getList(); } },error2 => { console.log(error2); } ); DataService getList()在这里创建一个公共变量,用getList()的响应更新它,然后导航到/ 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); } )}; 主页组件现在,在更新列表返回后,我们将导航到主页,并且已准备好显示更新的列表,而无需手动重新加载页面. 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您可以在此处检查更新列表的存在.如果存在,请显示它.如果它不存在,请显示“loading ….”消息. <div class="list" *ngIf="listOfItems"> <!-- Display list here --> </div> <div *ngIf="!listOfItems"> Loading.......... </div> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |