阻止数组更改其值

时间:2019-04-04 11:47:59

标签: angular typescript

我已经配置了一个模拟服务,看起来像这样

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
    )
]

我在数据服务内部访问此模拟数组

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

然后通过这些方法在不同组件中更改特定文章的initialQuantity值

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

(这是initializeQuantity函数) 但是每次我再次请求该文章时,这些​​特定文章的initialQuantity都将设置为由initializeQuantity()函数获取的值。可以肯定的是,在重新加载页面之后,状态是相同的,并且一切正常,但是如果我处于当前应用程序状态,那么很遗憾,即使在模拟服务数据内部,initialQuantitiy值的更改也会更改为Deep。我以为我可以通过散布运算符多次复制模拟数组来谨慎地更改状态,但这显然无济于事。

有人知道我的问题与哪里有关吗?

非常感谢您的建议,祝您生活愉快!

1 个答案:

答案 0 :(得分:1)

您复制的数组可能具有不同的引用,但是每个数组中的article对象仍然相同。复制的数组并不是真正必要的。至少不符合您当前的要求。您需要做的是创建文章本身的副本:

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