andreasteich
andreasteich

Reputation: 153

Stop array from changing it's values

I've got a mock-service configured Looking like this

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

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() { }
}

And I'm changing the initialQuantity value of a specific article by These method inside a different component

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);
    }
  }
}

(It's the initializeQuantity function) But everytime I request the article again, the initialQuantity of These specific article is set to the value getting by the initializeQuantity() function. Sure after reloading the page the state is same and everything works well, but if I'm in the current application state, unfortunately the initialQuantitiy value changes change Deep even inside the mock-service data. I thought I carefully change the state by copying the mock Array several times by the spread Operator, but obviously this doesn't help.

Does anyone know where my Problem relates in?

Thank you very much in advice and have a great day!

Upvotes: 0

Views: 171

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

Your copied array might have a different reference, but the article objects inside each array is still the same. The copied array is not really necessary. At least not with your current requirements. What you need to do, is create a copy of the article itself:

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

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

    return { ...article}; // here you create a shallow copy of the object
  }
}

Upvotes: 1

Related Questions