Prevent the array from altering its values

I am utilizing a mock-service that is configured in the following way:

import { Article } from "./article";

export const ARTICLES: Article[] = [
    new Article(
        1, 
        'used', 
        5060639120949, 
        'Monster Energy', 
        'NLZ0930EG', 
        'Espresso Monster Vanilla + Espresso',
        'Ein Espressomischgetränk mit Taurin, Milch und Vanilla-Flavour.',
        '../../assets/monster-espresso-vanilla.jpg',
        2.00,
        1,
        12,
        0.2,
        8,
        15,
        8
    ),
    new Article(
        2, 
        'used', 
        4018931180179, 
        'G Data', 
        'NLZ0930EG', 
        'G Data Inernet Secuirty Lizenzurkunde',
        'Lizenzurkunde der Vollversion von G Data Internet Security.',
        '../../assets/gdata-lizenzurkunde.jpg',
        40.00,
        1,
        12,
        0.2,
        8,
        15,
        0
    ),
    new Article(
        3, 
        'used', 
        4101090000638, 
        'Staatl. Fachingen', 
        'NLZ0930EG', 
        'Mineralwasser Medium',
        'Mineralwasser Medium feinperlend und erfrischend.',
        '../../assets/staatl.-fachingen-medium.jpg',
        0.89,
        1,
        57,
        1,
        10,
        25,
        10
    )
]

I access this mock Array inside my data-service as shown below:

import { Injectable } from '@angular/core';
import { Article } from '../model/article';
import { ARTICLES } from '../model/mock-data';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  private articles: Article[] = ARTICLES;
  articleCopy: Article[] = [...this.articles];

  fetchNeededArticle(eanCodeOfNeededArticle: number): Article {
    console.log(eanCodeOfNeededArticle);
    console.log(this.articleCopy);
    console.log(this.articleCopy.find(key => key.eanCode === eanCodeOfNeededArticle));
    const article: Article = this.articleCopy.find(article => article.eanCode === eanCodeOfNeededArticle);
    console.log('Ich wurde gefunden: ' + article);
    return article;
  }

  constructor() { }
}

I have created a method within a different component to change the initialQuantity value of a specific article as follows:

import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';
import { Article } from 'src/app/model/article';
import { DataService } from 'src/app/services/data.service';

@Component({
  selector: 'app-article-preview',
  templateUrl: './article-preview.component.html',
  styleUrls: ['./article-preview.component.css']
})
export class ArticlePreviewComponent implements OnInit {

  @Input() eanCodeOfNeededArticle: number;

  @Output() upcomingStep = new EventEmitter<string>();
  @Output() fetchedArticle = new EventEmitter<Article>();

  articleForConfiguration: Article;

  changeStep(upcomingStep: string): void {
    this.upcomingStep.emit(upcomingStep);
  }

  initializeQuantity(operation: string): void {
    switch(operation){
      case 'substract':
        this.articleForConfiguration.initialQuantity = this.articleForConfiguration.initialQuantity - 1;
        console.log(this.articleForConfiguration.initialQuantity);
        break;
      case 'add':
        this.articleForConfiguration.initialQuantity = this.articleForConfiguration.initialQuantity + 1;
        break;
    }
  }

  fetchNeededArticle(eanCodeOfNeededArticle: number): void {
    const newArticle = this.dataService.fetchNeededArticle(eanCodeOfNeededArticle);
    this.articleForConfiguration = newArticle;
  }

  constructor(private dataService: DataService) { }

  ngOnInit() {
    console.log('Wir brauchen dich: ' + this.eanCodeOfNeededArticle);
    if(this.eanCodeOfNeededArticle) {
      this.fetchNeededArticle(this.eanCodeOfNeededArticle);
    }
  }
}

However, every time I request the article again and change the initialQuantity value using the `initializeQuantity()` function, it affects not only the current application state but also changes deeply inside the mock-service data. Despite my efforts to carefully manage the state by making copies of the mock Array multiple times using the spread operator, this issue persists.

Can anyone help me identify where the problem lies?

Thank you in advance and have a wonderful day!

Answer â„–1

When you copy an array, the reference may change but the objects inside will remain the same. In this case, creating a copied array might not be necessary for your current needs. What you should do instead is create a duplicate of the individual article:

export class DataService {
  private articles: Article[] = ARTICLES;

  fetchNeededArticle(ean: number): Article {
    const article = this.articles.find(article => article.eanCode === ean);

    return { ...article}; // This line creates a shallow copy of the object
  }
}

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

How can one access a dynamically generated element in Angular without using querySelector?

Currently in the process of developing my custom toastr service, as shown in the GIF below My Objective: https://stackblitz.com/edit/angular-ivy-tgm4st?file=src/app/app.component.ts But without using queryselector. It's recommended to avoid querysele ...

What is the best way to trigger a function in the parent component when a child component is clicked

I'm facing a scenario where I have two components - a parent and a child. Within the child component, there is a button. My goal is to trigger a method in the parent component when the user clicks on that button within the child component. Any ideas o ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

Investigating the Angular signals that triggered the effect

Is there a way to determine which Angular signal triggered an effect? I have two signals and one effect in a component. One signal is used to start a timer function within a service, while the other signal reacts to changing conditions in the timer functio ...

What is the process for determining URL permissions?

Is there a way for me to control the permissions of the URLs that users are attempting to access? I have disabled buttons and other elements that could lead them there based on backend permissions, but I also want to prevent them from accessing those pages ...

Utilizing custom types in React with TypeScript and Prop-Types

Currently, I am working with a string type literal that looks like this: type MyType = 'str1' | 'str2' | 'str3'. I need one of my props to only accept this specific type, but I'm struggling to specify this in PropTypes. ...

The Instagram Basic Display API encounters an issue when processing a request for a user profile that does

Following the migration of our code from legacy api to basic display, we encountered an issue where no media is being retrieved for users who have not set their age in their profile. Instead, we are consistently receiving the following error: { "err ...

After a duration of 4 minutes, an ERR_EMPTY_RESPONSE is thrown in response to the

My angular 5 node app involves sending a request to the server and waiting for a response. There are instances where the response takes around 5-6 minutes to arrive. However, an ERR_EMPTY_RESPONSE error is triggered by the http method after just 4 minutes ...

What could be causing the elements in my array to appear as undefined?

https://i.stack.imgur.com/ze1tx.png I'm stuck trying to understand why I can't extract data from the array. const usedPlatformLog: Date[] = [] users.forEach(el => { usedPlatformLog.push(el.lastUsed) }) console.log(usedPlatformLog) // disp ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

"Implementing a unique constraint in Drizzle-orm PostgreSQL with the additional condition of deleted_at being

Is there a way to construct a table using a WHEN SQL tag? I am interested in setting up a table similar to this: "members_table", { id: serial("id").primaryKey(), email: text("email").notNull(), team_id: text(&q ...

``I'm facing an issue with Ionic 4's npm run build --prod command not functioning properly when deploying

Embarking on my first project with Ionic 4, I have previously worked with Ionic 3 where I used to build for the web using the command: npm run build --prod However, when attempting to build the Ionic 4 project with the same command, it generates an exces ...

Creating React components with TypeScript: Defining components such as Foo and Foo.Bar

I have a react component defined in TypeScript and I would like to export it as an object so that I can add a new component to it. interface IFooProps { title:string } interface IBarProps { content:string } const Foo:React.FC<IFooProps> = ({ ...

A guide to sending epoch time data to a backend API using the owl-date-module in Angular

I have integrated the owl-date-time module into my application to collect date-time parameters in two separate fields. However, I am encountering an issue where the value is being returned in a list format with an extra null value in the payload. Additiona ...

Tips on troubleshooting the issue when attempting to use a hook in your code

I am trying to implement a hook to manage the states and event functions of my menus. However, when I try to import the click function in this component, I encounter the following error: "No overload matches this call. The first of two overloads, '(p ...

Creating dynamic DOM elements in Angular templates by utilizing variable values as element types

There's a component I'm working with that I want to render either as a div or span dynamically. To achieve this, I've created an input variable called elementType. Now, the challenge is how to properly render it in the template. Here's ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this: let myarr = [{id:1 , name: "mark" , birthday: "1990-08-18"}, {id:2 , name: "fred" , birthday: "1990-08-17"}, {id:3 , name: "franck" , birthday: "1990-08-16"}, ...

Exploring ways to transform my function into rxjs in Angular

I have successfully implemented a function that is working as intended. Now, I am looking to transform it into an rxjs function with a filter in the rxjs directory. This transformation should involve using both the pipe method and includes method for filte ...

Setting button height dynamically in React Native

I've implemented a button using React Native Elements in my layout. Here's the code snippet: <Button title="Login" buttonStyle={{ backgroundColor: Colour.green }} containerStyle={{ ...