2017-02-20 17 views
1

正如另一個問題所述,我正在開發一個使用Firebase作爲後端的Ionic 2應用程序。AngularFire2:使用RxJS .map()執行FirebaseListObservables上的'連接'

我有類別,我有產品。產品屬於類別。由於它是「從n到m」的關係,因此產品和類別存儲在Firebase的不同節點中。我構造的數據如下:

Firebase data structure:

類別知道,哪些產品屬於他們(按鍵在每個類別中的「刺針」節點引用)。產品知道它們屬於哪個類別(密鑰在「prod_cat」節點中引用)。 但是,當我列出所有類別時,我只知道屬於該類別的產品的ID。在模板中,我需要顯示更多詳細信息,例如產品名稱。

我看過不少類似的問題的想出了這個解決方案的產品信息添加到類:

getProductsOfCategory(catId){ 
    this.productsOfCategory = this.af.database.list('/categories/'+catId+'/prods'); 

    return this.productsOfCategory 
    .map(products => { 
     console.log(products); // works fine: an object containing the relevant product information is logged to the console (see screenshot) 
     products.map(product => { console.log(product.$key); // works fine: the IDs of the products are logged to the console 
     product.prod_details = this.af.database.object('/products/'+product.$key); // seems not to work. Returned value: undefined 
     }); 
    }); 

不幸的是,這是行不通的。 作爲寫爲代碼中的註釋,所述產品信息被正確地收集並記錄到控制檯(見下圖): console screenshot

然而,上述功能的返回的對象是「未定義」。

當我嘗試狀態,類型FirebaseListObservable的是明確地定義一個目的是要返回,我收到錯誤:

Type 'Observable' is not assignable to type 'FirebaseListObservable'. Property '$ref' is missing in type 'Observable'.

沒有任何人有一個想法,還有什麼我可以嘗試?

非常感謝您提前!

回答

0

我解決了這個問題。

提供商(* .TS):

getProductsOfCategory(catId){ 
    let result = this.af.database.list('/categories/'+catId+'/prods') 
    .map(items => { 
     for (let product of items) { 
     this.af.database.object('/products/'+product.$key) 
     .subscribe(data => { 
      product.details = data; 
     }); 
     } 
     return items;   
    })  
    return result; 
} 


getCategoriesAndProducts(){ 
    let result = this.af.database.list('/categories') 
    .map(items => { 
     for (let category of items) { 
     this.getProductsOfCategory(category.$key) 
     .subscribe(data => { 
      category.productDetails = data; 
     }) 
     } 
     return items; 
    }) 
    return result; 
} 

提供商的呼叫在tempaltes TS文件:

getCategoriesAndProducts(){ 
    this.categoryService.getCategoriesAndProducts() 
     .subscribe(data => { 
      this.categoriesAndProducts = data; 
}); 

模板/視圖(*。html的):

<ng-container *ngFor="let cat of categories"> 
    <ng-container *ngIf="cat.parent_cat === 'noParentCategory'"> 
    <h3> 
     {{cat.cat_name}} 
    </h3> 
    <ng-container *ngFor="let subcat of categoriesAndProducts"> 
     <ion-list> 
     <ng-container *ngIf="subcat.parent_cat === cat.$key">    
      <ion-item-divider> 
      {{subcat.cat_name}} 
      </ion-item-divider> 
      <ion-item *ngFor="let prod of subcat.productDetails"> 
      {{prod.details?.prod_name}} 
      </ion-item> 
     </ng-container> 
     </ion-list> 
    </ng-container> 
    </ng-container> 
</ng-container>