首页 > 解决方案 > 如何在不刷新页面的情况下更新视图中显示的数据?

问题描述

我有一个用例,用户可以在其中收藏一个项目。下面的代码显示了我如何从数据库中检索数据以显示在视图中。

最喜欢的服务

   async getfavoriteList(): Promise<firebase.firestore.QuerySnapshot> {
    const user: firebase.User = await this.authService.getUser();
    if (user) 
          {
    this.FavoriteListRef = firebase
      .firestore()
      .collection(`userFavorites`);
    return this.FavoriteListRef.where('uid', '==', user.uid).get();
              }
           } 
       }

收藏夹.ts

ngOnInit() {    this.favoriteService.getfavoriteList().then(favoriteListSnapshot => {
      this.favoriteList = [];
      favoriteListSnapshot.forEach(snap => {
        this.favoriteList.push({
          id: snap.id,
          favoriteList: snap.data().favourite
        });
        console.log(snap.data().favourite)
        return false;
      });
    }); 

  }

我遇到的问题是,当用户收藏某个项目并转到收藏页面查看收藏的项目时,除非刷新页面,否则视图不会更新。这不是理想的用户体验。如何在不刷新页面的情况下更新视图。我尝试将代码放在构造函数以及 ngOnInit() 中,但页面没有更新。

标签: angulartypescriptionic-frameworkgoogle-cloud-firestore

解决方案


我建议你使用Observableover a promise。这将帮助您在不重新加载的情况下获取数据。

参考官方文档


推荐阅读