Encountering duplication issues when pushing objects into an array in Angular

Using EventEmitter in a service

toshoppinglist = new EventEmitter<Ingredients[]>()

Emitting method

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

Subscribing to the emit event and pushing the emitted values

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

      )

Currently, when pushing new values into the array, they are getting duplicated. It works fine for the first push but duplicates after that.

Answer №1

Personally, I believe that EventEmitter should only be used within DUMB components to trigger events in Smart components, not within services. Additionally, there could be a problem with duplication if the same ingredient is emitted each time a button is clicked without checking for differences in the new ingredients. To avoid duplicates, it's important to include logic in the subscribe function to push only new ingredients into the list.

Answer №2

To enhance your subscription function, be sure to incorporate a validation check.

Declare an array variable called currentIngredients to hold Ingredients objects.

Implement the following code snippet within your subscription service:

this.subscriptionService.toshoppinglist.subscribe(
    (ingredients: Ingredients[]) => {
       
        // Insert an if statement here to compare incoming ingredients with the currentIngredients array
        
        for(let item of ingredients) {
            if(this.currentIngredients.includes(item)) {
                // Increment the count of the existing ingredient
                this.currentIngredients[item].count++; 
            } else {
                // Add new ingredients that do not exist in the list
                this.currentIngredients.push(item);
            }
        }
});

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Within my component, I have incorporated two datepickers. My goal is to emit an object containing the values of both the start date and end date (referred to as startDateValue and

I have attempted to tackle this issue, but I am encountering the problem of receiving the same date value for both inputs. export class DateComponent implements OnInit { @Input() startDate: string; @Input() endDate: string; @Output() sendDate: Event ...

Arrange numbers in pairs and exchange them with neighboring pairs: [1,2,3,4,5,6] becomes [2,1,4,3,6,5]

public static void swap(int [] array) { for (int i = 0; i < array.length-1; i++) { int temp = array[i+1]; array[i+1] = array[i]; array[i]=temp; } } This particular code aims to interchange every two neighboring elements. ...

Error encountered when attempting to upload a file using Angular and Firebase: "[object Object]"

UPDATE : After some investigation, I finally discovered the solution which required specifying the file name in the reference : this.fireStorage.storage.ref(file.name).put(file); I have been attempting to upload a file to FireStorage, but I am encounteri ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

What is the best way to dynamically reorganize an array using PHP or SQL?

In my PHP script, I have a dynamic array that stores information about items including their item ID, store ID, and price for each store. As new store IDs are added, this array will expand accordingly. array (size=6) 0 => array (size=3) &apo ...

Altering the order or structure of an array or object in Vue

At this moment, Vue is calling a NAPI within the mounted function to retrieve the value for teambytime2. The API call appears like this: https://i.sstatic.net/FvL2A.png Shown below is the Axios GET URL used to fetch the data and assign it to this.teamByT ...

Obtaining a dependency directly from the Injector within a directive

I am currently working on developing a versatile directive that can take a class type for validating rules. Depending on the rule specified in the class, the directive will either display or hide an element. This is my progress so far. Check out the PLUN ...

Issue with HttpClient causing malfunction

I'm currently using Angular 4 and have decided to transition to using HttpClient. However, I've encountered a JSON parsing error that has proven quite challenging to fix despite extensive research. Previous Method import { Injectable } from &ap ...

Choose a Spot on the Open Layers map using a marker or icon

As a beginner in the world of Open Layers, I'm eager to learn how to utilize markers or icons to obtain user location. Additionally, I hope to harness the power of Angular to extract these location details. ...

Implementing Angular with Django - A Guide to Seamless Integration

My project calls for the development of an application utilizing Angular (TypeScript) for the frontend and Django for the backend. My focus will be solely on the Django backend. Will creating a REST API be adequate for communicating with the frontend in th ...

Is it possible for MATLAB to execute a function on a collection of objects?

I am looking to apply a function defined in the methods section of a class to all objects in an array simultaneously. The class I am working with looks like this: classdef myClass properties x=0; end methods ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

rxjs subscriptions in Angular

When setting up a subscription in Angular, I am declaring it as follows: counterSubscription: Subscription However, an error is being thrown stating: Property 'counterSubscription' has no initializer and is not definitely assigned in the const ...

Issue regarding custom CSS implementation in Angular project

Being a French speaker, I apologize in advance for any mistakes I might make. I am also fairly new to Angular, so if you could provide detailed explanations in your responses, it would be greatly appreciated. Thank you. I am trying to import a custom CSS ...

Unlocking the potential of styled-components by enhancing props and distributing them to children components

I'm currently puzzled trying to figure out how to enhance styled components to pass a couple of props to its children while ensuring proper linting with TypeScript. Here's what I currently have: // ButtonBase.tsx export const ButtonBase = styled ...

The subscribe function is not being triggered by the RxJS Angular 2 subject

As a newcomer to rxjs, I am currently facing an issue with the subscribe function in my code. Here's an example of what I'm working with: In Component A: getAllData() { this.dataService.getDataA().subscribe( data => console.log(data) ...

Using DevExtreme Angular to establish an initial filter value for a DxDataGrid custom headerFilter

What is the best way to set a starting headerFilter value with a custom expression like this? Using filterValues="xxx > 0" does not seem to work. <dxi-column caption="" dataField="xxx" [headerFilter]="headerFilter ...

Error: index out of range:0

I am currently working on a code that allows for controlling LEDs through voice commands. However, I have encountered an array out of bound exception error in the initialize function at line 2. Could someone please assist me in resolving this issue? Str ...

Generating all combinations of multi-dimensional objects within an array with variable length, also known as the Cartesian product

While there are numerous solutions available on StackOverflow and a helpful article on RosettaCode demonstrating how to find the Cartesian product for simple arrays, I have encountered a unique challenge for which I can't find a suitable solution. My ...

How to use MongoDB aggregate to filter out documents with non-empty arrays

I can't figure out how to write an aggregate query in MongoDB for a collection that has a field called "events", which is an array. The query needs to check if the events array is not empty. What I am looking for is something along the lines of: db.c ...