为什么Angular 4 ngModel会更改另一个变量?

时间:2017-11-02 02:08:37

标签: angular

我在Angular 4 ngModel中发现了有趣的错误。 成分:

this.restService.getProduct(this._id).subscribe(
   response => {
     this.product = response;
     this.productCategory = response.category;
...

模板:

<select [(ngModel)] = "productCategory._id" class="form-control form-
control-sm" id="category">
    <option *ngFor="let category of existedCategories | orderBy: 'name'" 
    value="{{category._id}}">{{category.name}}</option>
</select>

当我在模板中更改productCategory._id的ngModel值时,this.product.category._id的值也会更改。并且此检查返回false:

if (this.product.category._id !== this.productCategory._id) {
 observables.push(
  this.restService.changeProductCategory(this.product.category._id, 
  this.productCategory._id, this.product._id));
}

我找到了绕过这个的一些解决方案:

this.restService.getProduct(this._id).subscribe(
  response => {
    this.product = response;
    const resp = JSON.parse(JSON.stringify(response));
    this.productCategory = resp.category;

但仍然不明白为什么会这样。

2 个答案:

答案 0 :(得分:0)

因为你做了参考。如果您需要其他行为,则必须进行克隆。 在lodash中有cloneDeep。

答案 1 :(得分:0)

因为productCategory指的是product.category所在内存中的相同位置。

这不是Angular 4的错误。这是参考类型的工作原理。我正在附上学习链接:https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0