javascript - 克隆对象并更新 View

标签 javascript angular

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

正如您所看到的,它运行良好,但 View 没有更新。我该如何更新更改 View ?

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

还有一个问题,如何修改将路径传递给函数的 number.third 的值,例如:“number. Three”? :在这里回答:https://stackoverflow.com/a/8817473/5627096

应用程序组件

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

对象服务

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>

最佳答案

您需要在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

关于javascript - 克隆对象并更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851256/

相关文章:

angular - IE9 PathLocationStrategy Angular 4

angular - Angular 5 中的参数化路由

Angular 2 RC 6 Material 2 Alpha 8 不工作

Angular2 - 导入 Angular 模块

angular - Angula2 Karma 无法加载 "webpack"!

javascript - Postgres - 使用什么列类型来存储嵌套数组

javascript - 动态附加项目时,masonry 不会将它们布局出来

javascript - 如何将日期字符串转换为特定时区

javascript - 拖放 - 拖动一个已经放下的项目

javascript - 如何在客户端 (JavaScript) 上使用服务器端 (VB.NET) 的返回值?