我是 angular 5 的新手,我正在制作一个简单的购物车来学习 angular 5。我陷入了一种情况,我对如何检查购物车数据中的重复条目感到困惑。实际上问题是我很困惑我应该将对象存储在数组中还是数组中存储对象来存储数据。
这就是我在做的 首页组件
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
items: Array<object> = [];
total_items:Number = 0;
cart = {};
broadcast_obj = {items:[],totals:{}};
total_sum:Number = 0.0;
htmlToAdd:String = '';
constructor(private _data: DataService) { }
ngOnInit() {
//this.items_count = this.cart.length;
this._data.cast.subscribe(res => this.broadcast_obj = res);
this._data.changeCart(this.broadcast_obj);
}
additem(id,itemText,amount){
this.total_items = 10;
this.total_sum += amount;
this.cart = {id:id, name: itemText, price: amount,quantity:1};
if(this.items.length>0){
this.items.find(x => x.id == 3);//error id does not exist on type object
}
this.items.push(this.cart);
this.broadcast_obj.items = this.items;
this.broadcast_obj.totals = {total_items:this.total_items,total_sum:this.total_sum};
console.log(this.broadcast_obj)
//this._data.changeCart(this.broadcast_obj);
}
}
我将数据存储在 2 个对象中并将它们插入数组 1- {id:id, name: itemText, price: amount,quantity:1}; 2- {total_items:this.total_items,total_sum:this.total_sum};
现在我想检查 id 是否存在然后增加数量但我很困惑我做对了因为我在数组对象中搜索 id 并且它显示错误如注释中所示(类型对象上不存在 id ).
我也在想,如果我将对象存储在其 ID 的数组索引中,例如 如果项目 id=199,那么我将对象存储在数组索引 [199] 中,以便我可以快速搜索数组中的任何项目。
我仍然不知道从搜索 Angular 来看哪种方法更好,或者两者都是错误的。
请解决我的错误并帮助我以正确的结构存储购物车数据,以便我可以快速搜索商品并以可观察的方式传递购物车数据。
谢谢。
最佳答案
您因为这一行而收到错误:items: Array<object> = [];
这条线说 items
是一个对象数组(javascript 对象)。对象没有像 id 这样的属性。您需要为您的项目创建一个界面:
interface ICartItem {
id: number;
name: string;
price: number;
quantity: number;
}
然后在你的组件中你可以做 items: ICartItem[] = [];
(与 items: Array<ICartItem> = [];
相同)这将使错误消失。
您的组件:
// ...
items: ICartItem[] = [];
cart: ICartItem; // no need to initialise it with empty object
//...
关于javascript - 如何以 Angular 5 检查购物车中的重复项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48894623/