Angularfire2如何合并两个列表

Angularfire2 how to combine two list

我正在使用 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 异步中同时显示购物车和产品列表的数据

假设您有这样的结构:

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>