克隆对象和更新视图

时间:2018-02-18 11:42:41

标签: javascript angular

我有一个简单的服务来更新对象。我深度克隆了初始对象并更新了克隆。

如您所见,它运行良好,但视图未更新。如何更新有关更改的视图?

以下是代码:https://stackblitz.com/edit/angular-eh4cds?file=app%2Fapp.component.ts

另一个问题是,如何修改number.three的值,将路径传递给函数,如:" number.three" ? :在这里回答:https://stackoverflow.com/a/8817473/5627096

AppComponent

import { Component, OnInit } from '@angular/core';

import { ObjectService } from './object.service';

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

  private object: any;

  constructor (private objectService: ObjectService) {}

  ngOnInit () {
    this.object = this.objectService.getObject();
  }  

  changeObject () {
    this.objectService.changeObject('two', 'I\'m the one you need')
  }
}

ObjectService

import { Injectable } from '@angular/core';

@Injectable()
export class ObjectService {
    public object = {
      one: 'One',
      two: 'Two',
      number: {
        three: 'Three'
      }
    }

    public getObject () {
      return this.object;
    }

    public changeObject (path: string, value: any) {
      console.log('initial', this.object, path, value);
      let clone = { ...this.object, [path]: value };
      console.log('clone', clone);
      return this.object;
    }
}

查看

{{ object.one }}
<br>
{{ object.two }}
<br>
{{ object.number.three }}
<br>

<button (click)="changeObject()">Change object</button>

1 个答案:

答案 0 :(得分:1)

您需要在 changeObject

中分配返回的值
  changeObject () {
    this.object =  this.objectService.changeObject('two', 'I\'m the one you need');

  }

另外我认为你需要返回克隆的而不是对象

   public changeObject (path: string, value: any) {
      console.log('initial', this.object, path, value);
      let clone = { ...this.object, [path]: value };
      console.log('clone', clone);
      return clone;
    }

<强> STACBKLITZ DEMO