发现很难将显示在控制台上的数据显示在视图中

Finding it difficult to display data that is displayed on the console to display in the view

我有一个如下所示的 Firestore 数据库。 我目前正在从 userFavorites collection 中检索数据。

我最喜欢的服务

   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

  favoriteList: any; 
  public favoriteListRef: firebase.firestore.CollectionReference;


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

现在,当我 console.log 使用此数据时 -- console.log(snap.data().favourite) ,

我在控制台看到了数据。

但是,此数据未显示在具有以下内容的视图中 HTML 我已经尝试过。 我还尝试使用 JSON 管道转储数据。

<ion-grid>
        <ion-row>
        <ion-col size="12" >
        <ion-card *ngFor ="let favorite of favoriteList">
           <!--  <img [src]="favorite?.image[0]">
            <img [src]="favorite?.favorite.image[0]"> -->
          <div class="card-title">{{ favorite | json }}</div>
        <div>{{favorite?.description}}</div>
        </ion-card>
        </ion-col>
      </ion-row>
      </ion-grid>  

我做错了什么?

您似乎在 favoriteList<ion-card *ngFor ="let favorite of favoriteList"> 之间循环。 favoriteList 的结构是一个对象数组,每个对象都有 idfavoriteList 数组。

{
  id: snap.id,
  favoriteList: snap.data().favourite
}

在您的模板中,您正试图访问 favoriteList 上不存在的属性。

您已经创建了一个数组:

this.favoriteList = [];

那么你正在推送一个项目:

 this.favoriteList.push({
      id: snap.id,
      favoriteList: snap.data().favourite
    });

所以你有嵌套数组:

 favoriteList[i].favoriteList // you should iterate here

所以代码应该是这样的:

    <ion-card *ngFor ="let favorite of favoriteList">   
        <ng-container *ngFor="let item of favorite?.favoriteList">
            <img [src]="item.image[0]">
            <div class="card-title">{{ item | json }}</div>
            <div>{{item?.description}}</div>
        </ng-container>
    </ion-card>

由于您以异步方式填充数组,因此 html 第一次解析数组时它仍然是空的。但是,由于您在填充该数组时并未为其提供新的引用,因此 Angular 不会刷新其视图。因此,您要么需要 运行 在知道数组已满后手动更改检测,要么可以执行以下操作:

private favoriteListDisplay = new BehaviourSubject<any[]>([]);

然后您可以代替 console.log 执行以下操作:

this.favouriteListDisplay.next(this.favoriteList)

然后是你的 html:

 <ion-card *ngFor ="let favorite of favoriteListDisplay | async">

通过这种方式,您将告诉 angular 触发另一个检测变化和显示数据的周期。