正如另一个问题所述,我正在开发一个使用 Firebase 作为后端的 Ionic 2 应用程序。
我有类别,我有产品。产品属于类别。由于它是“n 到 m”的关系,因此产品和类别存储在 firebase 中的单独节点中。我将数据结构化如下:
Firebase 数据结构:
类别知道哪些产品属于它们(键在每个类别的“prods”节点中引用)。产品知道它们属于哪些类别(键在“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
});
});
不幸的是,这不起作用。
正如代码中的注释所写,产品信息已正确收集并记录到控制台(请参见以下屏幕截图):控制台截图
然而,上述函数的返回对象是“未定义”的。
当我尝试明确声明要返回 Firebase List Observable 类型的对象时,我收到错误:
类型“Observable”不可分配给类型“FirebaseListObservable”。
“Observable”类型中缺少属性“$ref”。
有人知道我还可以尝试什么吗?
预先非常感谢您!
我解决了这个问题。
提供商(*.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;
}
模板 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)