gpt4 book ai didi

javascript - AngularFire2:使用 RxJS .map() 在 FirebaseListObservables 上执行 'Joins'

转载 作者:行者123 更新时间:2023-11-28 04:58:21 26 4
gpt4 key购买 nike

如另一个问题所述,我正在使用 Firebase 作为后端开发 Ionic 2 应用程序。

我有类别和产品。产品属于类别。由于它是“n 到 m”的关系,因此产品和类别存储在 firebase 中的单独节点中。我的数据结构如下:

Firebase data structure:

类别知道哪些产品属于它们(键在每个类别的“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
});
});

不幸的是,这不起作用。正如代码中的注释所写,产品信息已正确收集并记录到控制台(请参见以下屏幕截图): console screenshot

但是,上述函数的返回对象是“未定义”的。

当我尝试明确声明要返回 FirebaseListObservable 类型的对象时,我收到错误:

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

有人知道我还可以尝试什么吗?

提前非常感谢您!

最佳答案

我解决了这个问题。

提供商 (*.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;
});

模板/ View (*.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>

关于javascript - AngularFire2:使用 RxJS .map() 在 FirebaseListObservables 上执行 'Joins',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com