在Angular 5中更新数据库后刷新组件

前端之家收集整理的这篇文章主要介绍了在Angular 5中更新数据库后刷新组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含路由/ 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.getList()中调用导航,以确保它等待来自getList()调用的响应.

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>

猜你在找的Angularjs相关文章