首页 > 解决方案 > Angular 6 属性绑定无法与多级对象一起正常工作

问题描述

我有一个新的应用程序,我正在制作一个宠物项目,但我的一个组件出现了错误。

我有一个复杂的对象来存储 D&D 怪物的信息。该组件用于带有加号和减号按钮的选项数量更改器,用于增加和减少数量。

当我将它用于第 1 层孩子(即 monster.strength)时,它可以正常工作,并且会增加到最大数量,并下降到基值(但不低于基值)当我将它用于第 2 层孩子时( ie. monster.speed.base) 它会正确递增,但它实际上会改变 basemonster 的值以及 selectedmonster 从而阻止递减工作。

下面的代码显示了如何将对象添加到文档中。

<option-quantity *ngIf="mod.location === 'base'"
     [max]="90"
     [step]="5"
     [costval]="mod.cost" 
     [baseval]="baseMonster[mod.type][mod.location]" 
     [(totalcost)]="selectedMonster.cost" 
     [(optval)]="selectedMonster[mod.type][mod.location]">
 </option-quantity>

这是组件TS文件

import { Component, Input, Output } from '@angular/core';
import { EventEmitter } from '@angular/core';

@Component({
  selector: 'option-quantity',
  templateUrl: './option-quantity.component.html',
  styleUrls: ['./option-quantity.component.css']
})
export class OptionQuantityComponent {
  @Output('optvalChange') emitter1: EventEmitter<number> = new EventEmitter<number>();
  @Output('totalcostChange') emitter2: EventEmitter<number> = new EventEmitter<number>();
  @Input('baseval') set setBaseVal(value) {
    this.base = value;
  }
  @Input('optval') set setOptValue(value) {
    this.count = value;
  }
  @Input('costval') set setCostValue(value) {
    this.cost = value;
  }
  @Input('totalcost') set setTotalCostValue(value) {
    this.totalcost = value;
  }
  @Input('step') set setStepValue(value) {
    this.step = value;
  }
  @Input('max') set setMaxValue(value) {
    this.max = value;
  }

  step = 1;
  max = 10;
  base = 0;
  count = 0;
  cost = 0;
  totalcost = 0;

  increment() {
    if (this.count < this.max) {
      this.count += this.step;
      this.totalcost += this.cost * this.step;
      this.emitter1.emit(this.count);
      this.emitter2.emit(this.totalcost);
    }
  }

  decrement() {
    if (this.count > this.base) {
      this.count -= this.step;
      this.totalcost -= this.cost * this.step;
      this.emitter1.emit(this.count);
      this.emitter2.emit(this.totalcost);
    }
  }

  onChange() {
    this.emitter2.emit(this.totalcost);
    this.emitter1.emit(this.count);
  }

}

我已经验证问题出在第 2 层子节点上,因为我尝试将统计数据移至统计子节点,并将速度移至根节点。这使得统计数据停止工作并且速度正常。我可以将速度移动到对象的根部,但我宁愿不这样做。

使用这些值的组件是由该函数创建的 baseMonster 的 create-undead 组件:

  setBase() {
    this.baseMonster = Object.assign({}, this.selectedMonster);
    this.currentSize = this.baseMonster.size;
    this.previousSize = this.baseMonster.size;
  }

整个项目可以在我的GitHub repo中查看

更新:我尝试使用 Object.spread 而不是 assign,但这没有任何区别。如果我使用 Object.freeze 并对“baseMonster”对象进行深度冻结,则该对象不会更改,但是“selectedMonster”将停止更新其第 2 层子值。

任何帮助将不胜感激。

标签: javascriptjsonangular

解决方案


问题在于您进行复制的方式:

this.baseMonster = Object.assign({}, this.selectedMonster);

Object.assign 不会对对象进行深层复制,如下所述 “如果源值是对对象的引用,则它只复制该引用值。”

这个答案有一个简单的方法:

clonedObj = JSON.parse(JSON.stringify(originalObj))

这个另一个答案对这个主题有详细的解释。


推荐阅读