【问题标题】:How to update displayed data in the view, without refreshing the page?如何在不刷新页面的情况下更新视图中显示的数据?
【发布时间】:2020-03-11 19:28:27
【问题描述】:

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

最喜欢的服务

   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();
              }
           } 
       }

Favorite.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() 中,但页面没有更新。

【问题讨论】:

  • 你返回一个 Promise,它解决并完成。 Try docs and ask if needed
  • 我希望这个问题已经解决了一个多月。然而,如果不是这样,虽然我的背景来自 MERN 堆栈,并且我的大部分前端经验都来自 React,但我过去确实遇到过这种问题。对我来说,这是在正确的生命周期钩子中执行更新功能的问题。就我而言,它是componentDidUpdate(),只要有更改,我就会在其中更新组件的state 对象。我建议在 Angular 中尝试不同的生命周期,例如 ngOnChanges

标签: angular typescript ionic-framework google-cloud-firestore


【解决方案1】:

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

Refer official documentation.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2019-11-25
    • 2018-03-24
    相关资源
    最近更新 更多