Angular4 / AngularFire2从嵌套的JSON

时间:2017-09-19 18:18:55

标签: json angular firebase-realtime-database angularfire2

我在里面有一家餐馆,这是一个提示:

  

这里是JSON结构:http://prntscr.com/gn5de8

所以我首先尝试在我重复的餐厅内获取数据:

<p *ngFor="let tip of restaurants[item.$key].tips" [innerHTML]="tip.description"></p>

但这不行。

所以我尝试在component.ts中添加额外的内容:

public restaurants: FirebaseListObservable<any>;
public tips: FirebaseListObservable<any>;

constructor(private db: AngularFireDatabase) {
    this.restaurants = db.list('/restaurants');
    this.tips = db.list(`/restaurants/${key}/tips`);
}

然后尝试用以下方法重复它们:

<p *ngFor="let tip of tips | async" [innerHTML]="tip.description"></p>

但是在这里我在构造函数中的第二行出错:&#34;找不到名称&#39; key&#39;&#34;我的语法有什么问题?这就是我尝试做的,解决这个问题的正确方法吗?

如果您需要查看html和ts文件:

  

HTML:https://pastebin.com/6rEmmrXZ   TS:https://pastebin.com/e5CnPqYp

     

这里是我找到第二次尝试信息的来源:   Firebase / Angularfire2: nested data nodes in firebase

最好的问候。

1 个答案:

答案 0 :(得分:1)

您收到该错误是因为您没有在任何地方定义key变量。实现目标的一种方法是映射餐馆列表,然后将tips对象转换为每个餐馆的数组:

this.restaurants = db.list('/restaurants')
  .map(restaurants => restaurants.map(item => ({
    ...item,
    tips: Object.keys(item.tips)
      .reduce((acc, key) => [...acc, item.tips[key]], []);
  });
));

不要忘记导入map运算符(rxjs/add/operator/map)。然后,在您的HTML中,只需遍历餐馆列表:

<div *ngFor="let restaurant of restaurants | async">
  <div *ngFor="let tip of restaurant.tips">
    <p [innerHTML]="tip.description"></p>
  </div>
</div>

但是,我不建议采用这种方法。我认为您应该重新考虑数据结构和数据库调用。

您现在正在做的事情,您将调用整个提示列表以及餐馆列表。这将变得太昂贵。您应该分开提示列表:

- tips
  - $restaurantKey
    - $tipKey
      ...data

这样,您可以单独调用提示列表 - 仅在需要时。此外,我没有看到在餐馆列表中加载整个提示列表的重点。如果您的应用程序增长,并且您最终会为每家餐厅提供多个提示,那么这可能是一个巨大的问题。

相反,您可以获得提示摘要。选择餐厅后,您只会显示该餐厅的提示 - 而不是一次性加载所有内容。