2017-11-25 149 views
1

我正在使用Angularfire2 v5。在我的數據庫中,我有兩個列表,一個是cart,另一個是product。購物車列表中有一個包含產品ID的字段,現在我需要一個包含購物車及其產品數據的Observable。目前我使用這個Angularfire2如何合併兩個列表

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

這樣

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努力,但它讓我空。

回答

3

我怎麼能在一個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>