简体   繁体   中英

In angular Pushing objects in array getting duplicated

EventEmitter in service

toshoppinglist = new EventEmitter<Ingredients[]>()

Emitting method

toshoppinglist() {
    this.slservice.toshoppinglist.emit(this.item.ingredients);
  }
ingredients : Ingredient []

Subscribing to emit and pushing emitted values

this.slservice.toshoppinglist.subscribe(
        (ingredients: Ingredients[]) => {
          for (let item of ingredients) {
            this.ingredients.push(item);
          }
        }

      )

Now, when pushing new values into the array,it's getting duplicated.It's work fine for first pushing,but getting duplicated after that.

Ok, first in my opinion you use wrongly EventEmitter. Eventemitters used only inside DUMB components to raise an event to Smart component. And not inside services. Second, yes it will be duplicated. Imagine you have button which will raise this eventemitter and we emit the same ingredient every time. Inside the subscribe you didnt check that new ingredient are different. And because you use list, it doesnt care if you have duplicates. So a solution is to add to the subscribe a check that it will push only - new- ingredients.

You need to add a check in your subscription function.

currentIngredients: Ingredients[];

this.slservice.toshoppinglist.subscribe(
        (ingredients: Ingredients[]) => {
     
>    //here you need the if condition comparing it to a current
> ingredients array to see if it exists or not
  
   for(let item of ingredients) {
   if(this.currentIngredients.includes(item) {
// in this case you should increment the count of ingredient
   currentIngredients[item].count++; 
    }
  else {
 // this should only add non-existing items ingredients list
  this.currentIngredients.push(item)
}
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM