我是angular 5的新手,我正在制作一个简单的购物车来学习angular5。我陷入了一种困惑,即如何检查购物车数据中的重复条目。实际上,问题在于我对应该将对象存储在数组中还是将数组存储在对象中以存储数据感到困惑。

这就是我在做什么
家庭组件

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,名称:itemText,价格:金额,数量:1};
2- {total_items:this.total_summs,total_sum:this.total_sum};

现在,我想检查id是否存在,然后增加数量,但是我做错了,因为我正在数组对象中搜索id,并且它显示错误,如注释中所示(类型对象上不存在id)。

这是对象数组的当前结构
javascript - 如何在 Angular 5中检查购物车中的重复项目?-LMLPHP

我还想如果我将对象存储在其ID的数组索引中,例如
如果项目id = 199,则将对象存储在数组索引[199]中,以便可以快速搜索数组中的任何项目。

从搜索的 Angular 来看,我仍然不知道哪种方法更好,或者两者都是错误的。

请解决我的错误,并帮助我以正确的结构存储购物车数据,以便我可以快速搜索商品并以可观察的方式传递购物车数据。

谢谢。

最佳答案

由于出现以下行,您会收到错误消息:items: Array<object> = [];这句话说items是对象(javascript对象)的数组。对象没有ID等属性。您需要为您的项目创建一个接口(interface):

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
//...

10-04 22:55
查看更多