【问题标题】:Angularfire2 how to combine two listAngularfire2如何组合两个列表
【发布时间】:2018-05-09 09:59:20
【问题描述】:

我正在使用 Angularfire2 v5。在我的数据库中,我有两个列表,一个是cart,另一个是product。在购物车列表中有一个包含产品 ID 的字段,现在我想要一个包含购物车及其产品数据的 Observable。目前我正在尝试这种方式

cart: Observable<any>;
constructor(public db: AngularFireDatabase) {}

ionViewDidLoad() {

this.cart = this.db.list(`/cart`)
  .snapshotChanges()
  .map(changes => {
    return changes.map(c => {
      let productObservables:Observable<any> = this.db
        .list(`product/${c.key}`).snapshotChanges()
        .map(m=>{
            m.map(p=>({
              key:c.payload.key, ...p.payload.val()
            }));
            return m;
        });
        return productObservables;
    })
  });

现在在 html 中使用这个

<ion-item *ngFor="let item of cart|async">
  <ion-label>
    {{item.key}}
    {{item.name}}
  </ion-label>

但它显示我为空。如何在一个 ngFor async 中同时显示购物车和产品列表的数据

【问题讨论】:

    标签: firebase firebase-realtime-database ionic3 angularfire2 angularfire5


    【解决方案1】:

    假设你有这样的结构:

    cart:
      yyy:
        productId: aaa
        qty: 2
      zzz:
        productId: bbb
        qty: 1
    products:
      aaa:
        name: AAA
      bbb:
        name: BBB
    

    然后你可以将它映射到数据库的其他部分,因为你已经有了我在这里使用valueChanges() 的密钥。

    this.cart = this.db.list(`/cart`)
      .snapshotChanges()
      .map(changes => 
        changes.map(c => ({
          key: c.payload.key,
          product: this.db.object(`products/${c.payload.val().productId}`).valueChanges(),
          ...p.payload.val()
        }))
      );
    

    然后产品将是异步的,因此您也需要在视图中使用管道:

    <ion-item *ngFor="let item of cart | async">
      <ion-label *ngIf="item.product | async; let product; else loading">
        {{product.name}} x {{item.qty}} {{item.key}}
      </ion-label>
    <ion-item>
    <ng-template #loading><ion-spinner></ion-spinner></ng-template>
    

    【讨论】:

      猜你喜欢
      • 2012-10-15
      • 2014-07-31
      • 2020-07-19
      • 1970-01-01
      • 2016-08-08
      • 2021-10-31
      • 1970-01-01
      • 2022-09-27
      • 2015-11-08
      相关资源
      最近更新 更多