【问题标题】:How to check the duplicate item in cart in angular 5?如何在 Angular 5 中检查购物车中的重复项目?
【发布时间】:2018-07-31 08:49:45
【问题描述】:

我是 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 的数组索引中,例如 如果 item id=199 然后我将对象存储在数组 index[199] 中,以便我可以快速搜索数组中的任何项目。

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

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

谢谢。

【问题讨论】:

    标签: javascript jquery angular typescript


    【解决方案1】:

    由于这一行,您会收到错误消息:items: Array&lt;object&gt; = []; 此行表示items 是一个对象数组(javascript 对象)。对象没有像 id 这样的属性。您需要为您的项目创建一个界面:

    interface ICartItem {
        id: number;
        name: string;
        price: number;
        quantity: number;
    }
    

    然后在您的组件中您可以执行items: ICartItem[] = [];(与items: Array&lt;ICartItem&gt; = []; 相同)这将使错误消失。

    你的组件:

    // ...
    items: ICartItem[] = [];
    cart: ICartItem; // no need to initialise it with empty object
    //...
    

    【讨论】:

    • 或者直接运行items: Array&lt;any&gt; = new Array&lt;any&gt;();
    • @BorisLobanov 感谢您的回答。我应该把接口放在哪里,因为当我把它放在组件中时,整个类都充满了错误。
    • 你可以把它放在一个单独的文件中并导入(只需在声明接口之前添加export)或将它放在你的类/组件的上方或下方
    • @BorisLobanov 现在这条线是红色的 this.items.push(this.cart);错误:类型 {} 的参数不可分配给类型 icartItem
    • @BorisLobanov 我还编写了您的代码项: Array = [ ];但仍然是错误。
    【解决方案2】:

    我同意@BorisLobanov 接受的答案,我只是想我会添加第二个示例,说明您还可以如何实现这一目标...

    通过将items 定义为:items: Array&lt;any&gt; = new Array&lt;any&gt;(); 您还可以减轻这些错误。

    但是,正如我同意的@BorisLobanov 所述,请注意:

    使用 any 不是一个很好的做法,它使 Typescript 有点毫无意义


    ...在我看来,您可以使用any 类型的数组的一个地方是“项目”是从 API 调用派生的。这样做的原因是您可能会收到一个包含 100 个属性的对象数组。但是,您只想使用其中的 4 个属性...或者对于下面显示的示例,您需要数据达到某个值,但实际上并不关心数据本身。

    使用any 可以防止打字稿编译器(编译时没有错误)验证items 的类型结构,这反过来又允许您unsafely 访问您知道将存在的属性。


    当数据结构具有嵌套对象时,好处是显而易见的,例如:

    australianCities = [
      {
        name: 'Sydney',
        suburbs: [{
          name: 'town 1',
          houses: [{
              population: 3,
              address: 'aa'
            },
            {
              population: 1,
              address: 'bb'
            }
          ]
        }]
      }, ...
    ];
    

    考虑为这里的每个对象定义所有这些接口已经伤害了我的灵魂(想象一个实际上很复杂的接口),尤其是当 API 可以更改时,如果我想做的所有事情总人口数 在澳大利亚所有城市。

    但是,使用 any... 可以减少麻烦,例如:

    let sum = (accumulator, currentValue) => accumulator + currentValue;
    population = australianCities.map(city => city.towns.map(town => town.houses.map(house => house.population).reduce(sum)).reduce(sum)).reduce(sum);
    

    var australianCities = [{
        name: 'Sydney',
        suburbs: [{
          name: 'town 1',
          houses: [{
              population: 3,
              address: 'aa'
            },
            {
              population: 1,
              address: 'bb'
            }
          ]
        }]
      },
      {
        name: 'Perth',
        suburbs: [{
          name: 'town 1',
          houses: [{
              population: 10,
              address: 'aa'
            },
            {
              population: 2,
              address: 'bb'
            }
          ]
        }]
      }
    ];
    
    var sum = (accumulator, currentValue) => accumulator + currentValue;
    
    totalPopulation = australianCities.map(city => city.suburbs.map(town => town.houses.map(house => house.population).reduce(sum)).reduce(sum)).reduce(sum);
    
    console.log({
      totalPopulation
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2013-10-26
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多