[英]Interface logs as undefined though the products gathered from service call display on page
此问题是此处发布的先前问题的后续- 先前问题
我试图将数据放入Firebase数据库(特别是实时数据库)中,并且编写了一项服务,该服务将获取我所有的当前产品,然后将其用于创建购物车的方法中。
但是,尽管我可以在视图上获取并显示产品,但是我的服务继续返回未定义的结果。
我试图将数据手动放入接口,但是每次登录控制台时,都undefined
。
此服务方法用于从Firebase数据库检索产品:
getAll() {
this.itemRef = this.db.list('/products').snapshotChanges().pipe(
map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
})
);
return this.itemRef;
}
下面的代码片段显示了我在组件内部尝试完成的工作。
products$: Observable<ProdInterface>;
prodLook: ProdInterface[]
this.products$ = this.productService.getAll();
this.productService.getAll().subscribe(data =>
this.prodLook = [{
color_way: data.color_way,
description: data.description,
$key: data.key,
name: data.name,
photo: data.photo,
price: data.price,
qty: data.qty
}]
)
以上代码段的目标是将products$
传递给此方法:
//product returns undefined
async addToCart(product: ProdInterface, change: number) {
let cartId = await this.getOrCreateCart();
debugger
let item$ = this.getItem(cartId, product.$key);
item$.snapshotChanges().pipe(take(1)).subscribe(item => {
if (item.payload.exists()) {
let quantity = item.payload.exportVal().quantity + change;
if (quantity === 0) item$.remove();
else
item$.update({
product: item.payload.exportVal(),
quantity: quantity
});
} else {
item$.set({ product: item.payload.exportVal(), quantity: 1 });
}
})
}
编辑:用于绑定到addToCart
HTML
<div *ngIf='products$'>
<div class="row">
<div class="col-md-4" *ngFor="let product of products$ | async">
<mdb-card>
<!--Card image-->
<mdb-card-img [src]="product.photo" alt="Card image cap"></mdb-card-img>
<!--Card content-->
<mdb-card-body>
<!--Title-->
<mdb-card-title>
<h4>{{product.name}}</h4>
</mdb-card-title>
<!--Text-->
<mdb-card-text>
{{product.description}}
</mdb-card-text>
<span>
<mdb-card-text>{{product.price}}</mdb-card-text>
</span>
<button (click)="addToCartProd()" class="btn btn-primary btn-block">Add To Cart</button>
</mdb-card-body>
</mdb-card>
</div>
</div>
</div>
与HTML串联使用的addToCartProd方法
// addToCartProd(){
// this.cartService.addToCart(this.products$,1)
// console.log(this.products$)
// }
我的代码目标是将addToCart
附加到视图上的按钮,然后根据其键将正确的产品发送到数据库。 当前的实现将undefined
发送到数据库,这是造成混乱的原因,因为产品使用相同的getAll()
方法显示在页面上。
谢谢
您的模板应将product
从*ngFor
传递给addToCardProd()
。 您的模板和方法应类似于以下内容。
<div *ngIf='products$'>
<div class="row">
<div class="col-md-4" *ngFor="let product of products$ | async">
<mdb-card>
...
<button (click)="addToCartProd(product)" class="btn btn-primary btn-block">Add To Cart</button>
</mdb-card-body>
</mdb-card>
</div>
</div>
</div>
addToCartProd(product: ProdInterface){
this.cartService.addToCart(product,1)
console.log(products$)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.