javascript - 来自firebase的密钥问题 - 从我的界面返回未定义
问题描述
所以我在做 Mosh Hamedami 的在线课程。我或多或少一直在关注它,但一切正常。我可以将产品添加到 Firebase 并编辑/删除它们。现在我想实现一个“购物车”,我可以在其中添加一个特定的 CardId 并将 Items + 数量添加到该 cardId
但是,我遇到了一个问题,我想将产品添加到 firebase 购物车。添加带有 cartId 的购物车 - 时间戳有效。不知何故,我无法将项目添加到 cartId。
我猜我的 Observable 有问题……
控制台错误是:
_core.js:6260 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'key' of undefined
TypeError: Cannot read property 'key' of undefined_
at ShoppingCartService.<anonymous> (shopping-cart.service.ts:51)
它告诉我来自“addToCart”的产品未定义。
addToCart(product: Product) {
this.shoppingCartService.addToCart(product);
console.log(product);
}
此外,我的编译器告诉我采取的形式 .pipe(take(1)) 是:
_error TS2684:“void”类型的“this”上下文不可分配给“Observable”类型的方法“this”。
不知何故 pipe(first()) 工作,但与密钥相同的问题。
我尝试了很多无法弄清楚我的错误。我也是 Angular 的新手,所以..我真的很感激任何我必须寻找问题的提示。
购物车.service.ts
import {Injectable} from '@angular/core';
import {AngularFireDatabase} from "@angular/fire/database";
import {Product} from "./models/product";
import 'rxjs/add/operator/take';
import {take} from "rxjs-compat/operator/take";
import {pipe} from "rxjs";
import {Observable} from "rxjs";
import {first} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
constructor(private db: AngularFireDatabase) {
}
//create shopping cart in db + add date(timestamp)
private create() {
return this.db.list("/shopping-carts").push({
dateCreated: new Date().getTime()
});
}
private getCart(cartId: string) {
return this.db.object('/shopping-carts/' + cartId);
}
private getItem(cartId: string, productId: string) {
return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
}
//getting reference to shopping cart
private async getOrCreateCartId(): Promise<string> {
let cartId = localStorage.getItem('cartId');
if (cartId) return cartId;
// calls this.create and waits for the response
let result = await this.create();
//saves cartId in local storage and returns
localStorage.setItem('cartId', result.key);
return result.key;
}
//add new product to cart and safe localstorage
async addToCart(product: Product) {
const cartId = await this.getOrCreateCartId();
//reference to products in firebase cart
const item$ = this.getItem(cartId, product.key);
item$.snapshotChanges().pipe(take(1)).subscribe((item: any) => {
if (item) {
item$.update({product: product, quantity: (item.quantity || 0) + 1});
}
});
}
}
产品.ts
export interface Product {
key : string;
title : string;
price : number;
category : string;
imageURL : string;
}
调用 addToCart 的 html:
<div class="columns is-multiline is-narrow">
<ng-container *ngFor="let p of filteredProductsByCategory">
<div class="column is-one-third">
<div class="card">
<figure class="image is-square">
<img [src]="p.imageURL" alt="{{p.title}}">
</figure>
</div>
<div class="card-content">
<p class="title"> {{p.title}}</p>
<p class="subtitle">{{p.price | currency: "USD"}}</p>
<div
(click)="addToCart(product)"
class="button is-outlined is-primary"> Add to Cart</div>
</div>
</div>
</ng-container>
</div>
如果需要,我还可以将我的代码上传到 GitHub!谢谢!!
解决方案
// add new product to cart and safe localstorage
async addToCart(product: Product) { ... }
调用时很有可能addToCart
根本product
没有设置。您应该检查调用函数的位置(*.component.ts 或 *.component.html?),并且应该设置产品。
编辑:
我猜你想通过p
而不是product
. 尝试以下操作:
<div
(click)="addToCart(p)"
class="button is-outlined is-primary"> Add to Cart</div>
推荐阅读
- android - Intellij 中 Android 单元测试期间的日志给出 java.lang.RuntimeException: Stub
- python - Python 中的 JSON GET 和 POST
- firebase - 如何向 FirebaseAnimatedList 添加分页
- regex - 匹配基于正则表达式模式匹配的时间戳
- python - 使用数据框从 K-Means 集群中获取值
- javascript - Chrome mDNS api产生空设备列表
- javascript - 跨域请求被阻止:Braintree dropin UI
- git - 如何在提交消息中搜索多个单词?
- javascript - 如何制作 Geo IP 查找命令?
- java - 推断类型变量(S)