首页 > 解决方案 > Ionic + Firebase - 实时数据库不更新视图

问题描述

我的应用程序有一个非常奇怪的问题。为了显示实时数据库,我必须与应用程序交互。2个月前我没有这个问题,信息正常显示,但现在,我必须点击按钮或其他东西才能更新视图。

我在这里做了一个快速的GIF:

如果您在我单击<- back按钮时暂停,您会明白我的意思.. https://i.gyazo.com/44b450aa502dc7f37e5a5feea19824c6.mp4

我不知道我做了什么让这件事发生..

这是我的应用程序中的代码示例:

.ts

  if(fromClick) { this.subscription.off(); }
  this.postFeed = new Array();
  this.subscription = this.database.database.ref('/posts/'+this.locationId)
  .orderByChild('score')
  .limitToLast(10);
  this.subscription.on('child_added', (snapshot) => {
        this.postFeed.push(snapshot.val())
  });

.html

  <ng-container *ngFor="let post of postFeed.reverse(); let i = index">
    <post [postData]="post"></post>
  </ng-container>

因此,上面的代码过去可以完美运行,但现在我必须与我的应用程序交互才能将其显示在屏幕上,即使postFeed控制台记录得非常好。数据在我请求时准确地显示在控制台中,但它没有显示在屏幕上。

有任何想法吗?正如我所说,它曾经工作得很好。任何帮助都会很棒!谢谢

标签: javascriptangularionic-frameworkfirebase-realtime-databaseionic2

解决方案


对于其他有这个问题的人来说,这NgZone就是我的答案。

我导入了它:

import { NgZone } from '@angular/core';

将其添加到构造函数中:

public zone: NgZone,

然后将它包裹在我的firebase代码周围:

  this.zone = new NgZone({});
  if(fromClick) { this.subscription.off(); }
  this.postFeed = new Array();
  this.subscription = this.database.database.ref('/posts/'+this.locationId)
  .orderByChild('score')
  .limitToLast(10);
  this.subscription.on('child_added', (snapshot) => {
    this.zone.run(() => {
        this.postFeed.push(snapshot.val())
     }):
  });

这对我来说非常有用。我找不到问题的实际原因,但我只是将NgZone代码包裹在我所有的 firebase 函数中,它就像以前一样工作。如果其他人有更多信息,那就太好了。


推荐阅读