首页 > 解决方案 > 视口不显示从 ts 构造函数接收到的数据

问题描述

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

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

下面是我的代码::

主页.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() {}
}

主页.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>

标签: angulartypescriptionic-frameworkgoogle-cloud-firestoreionic3

解决方案


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

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

推荐阅读