【问题标题】:Viewport not displaying data received from ts constructor视口不显示从 ts 构造函数接收到的数据
【发布时间】:2020-07-11 16:45:22
【问题描述】:

我正在使用来自 Firestore 的 where 条件在构造函数中接收数据。 当我console.log 我看到我的数组 时,它不会反映在 viewport home.html 上,直到我单击页面上的任意位置或更改浏览器窗口 [比如打开其他窗口并返回此窗口]。

我的朋友指导我使用ChangeDetectorRef,我按照她的指导使用它。当我的数组准备好时,我已经调用了this.cd.detectChanges();,但它没有工作。

下面是我的代码::

home.ts

import { Component, OnInit } from "@angular/core";
import * as firebase from "firebase";
import { firestore } from "firebase/app";
import {
  AngularFirestoreCollection,
  AngularFirestore,
} from "@angular/fire/firestore";
import { ChangeDetectorRef } from "@angular/core";

@Component({
  selector: "app-test1",
  templateUrl: "./test1.page.html",
  styleUrls: ["./test1.page.scss"],
})
export class Test1Page implements OnInit {
  dailyreports: any = [];
  constructor(
    private firestore: AngularFirestore,
    private cd: ChangeDetectorRef
  ) {
    let start = new Date("2020-03-29");
    firebase
      .firestore()
      .collection("dailyreport")
      .where("timestamp", ">=", start)
      .onSnapshot((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          console.log(doc.id, " ===> ", doc.data());
          this.dailyreports.push(doc.data());
        });
        this.cd.detectChanges();
        console.log(this.dailyreports);
      });
  }

  ngOnInit() {}
}

home.html

<ion-content>
  <div
    class="info col-11"
    *ngFor="let list of this.dailyreports; let i = index;"
    (click)="openModaWithData(i)"
  >
    <div id="chtv">
      Click here to view what {{list.name}} did.
    </div>

    <div id="rcorners">
      {{list.name}}
    </div>

    <div id="rcorners2">
      {{list.timestamp}}
    </div>
    <br />
  </div>
</ion-content>

【问题讨论】:

  • 能不能把stackblitz里的代码分享一下,让我们看到实际的代码。

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


【解决方案1】:

您可以根据变量重新分配强制角度刷新(更改检测)。

firebase
  .firestore()
  .collection("dailyreport")
  .where("timestamp", ">=", start)
  .onSnapshot((querySnapshot) => {
    // Get new items
    const newItems = [];
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " ===> ", doc.data());
      newItems.push(doc.data());
    });
    console.log({ newItems });
    // Trigger change detection
    this.dailyreports = this.dailyreports.concat(newItems)
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 2011-02-17
    • 2018-05-28
    • 2015-11-09
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    相关资源
    最近更新 更多