【发布时间】:2016-12-23 12:19:16
【问题描述】:
我正在使用 Angular2 开发电子商务 Web 应用程序。
我已经在会话中保存了订购信息。
addToCart(productId:string,noOfItems:number):void{
let itemCounts;
let selectedItems=[];
if(sessionStorage.hasOwnProperty("cartItemCount"))
{
itemCounts = parseInt(sessionStorage.getItem("cartItemCount"));
itemCounts++;
sessionStorage.setItem("cartItemCount",itemCounts.toLocaleString());
}else{
sessionStorage.setItem("cartItemCount","1")
}
this._addtocartService.updateCount.emit("itemAdded");
this._notificationService.success("Success","item added to Cart");
let item={
productId:productId,
productName:this.productDetail.name,
packageName:this.selectedPackage.packageName,
Rate:this.selectedPackage.price,
unit:this.selectedPackage.unitPerQuantity,
quantity:noOfItems,
packageId:this.selectedPackage._id,
owner:this.owner._id
}
if(sessionStorage.getItem("CartContent") != undefined)
{
let test = JSON.parse(sessionStorage.getItem("CartContent"));
for(let loop=0;loop<test.length;loop++) {
if(test[loop].productId==productId) {
}
}
}
if(sessionStorage.hasOwnProperty("CartContent")) {
selectedItems=JSON.parse(sessionStorage.getItem("CartContent"));
}
selectedItems.push(item);
sessionStorage.setItem("CartContent",JSON.stringify(selectedItems));
console.log(sessionStorage.getItem("CartContent"));
}
我有 cartItem 组件,所有订购的信息都将在其中显示。在那个组件中,我从这样的会话中获得订购的物品。
export class cartItemComponent{
private Orders:any;
private total:number;
constructor(private dataService:DataService,
private loggerService:LoggerService){
this.getCartContent();
this.calculatePrice();
}
getCartContent(){
this.Orders = JSON.parse(sessionStorage.getItem("CartContent"));
console.log("from Orders");
console.log(this.Orders);
var products = JSON.parse(sessionStorage.getItem("product"));
}
calculatePrice() {
let i;
for (i = 0; i < this.Orders.length; i++) {
console.log("this is order");
console.log(this.Orders[i]);
this.dataService.post("order/prices", this.Orders[i])
.subscribe(res => {
console.log(res);
console.log(this.Orders[i]);
this.total+=res.totalPrice;
this.Orders[i]['totalPrice'] = res.totalPrice;
});
console.log("Total is " + this.total);
if(i==this.Orders.length){
this.loggerService.log(this.Orders,"green");
}
// setTimeout(()=>{
// for (i=0;i<this.Orders.length;i++){
// this.Orders[i]['totalPrice']=233;
// }
//
// console.log("inside timeout");
// },3000);
}
}
//}
}
我通过 calculatePrice() 方法将该信息传递给 api,以便仅从 api 获取每种类型商品的总价格。 但是在该订阅中,this.Orders[i] 是未定义的,我无法在其中添加新的 json 键 this.Orders[i]['totalPrice'] 及其值。
接下来我必须使用循环语句在表格中显示该信息。
我们将不胜感激
【问题讨论】:
-
请添加更多上下文。这段代码与上下文无关,我只能随机猜测它为什么不能按预期工作。
-
已编辑。谢谢@ppo
标签: javascript angular