【问题标题】:Clone object and update view克隆对象并更新视图
【发布时间】:2018-02-18 20:01:45
【问题描述】:

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

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

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

还有一个问题,我该如何修改number.three 的值,将路径传递给函数,例如:“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>

【问题讨论】:

  • 您可以使用Object.assign() 深度克隆您的对象
  • 是的,我知道,但你会遇到同样的问题。

标签: javascript angular


【解决方案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

【讨论】:

  • 是的,很好,它正在工作。 (你忘了更新 stackblitz)。关于我的第二个问题?
  • 没关系,我在这里找到了答案:stackoverflow.com/a/8817473/5627096
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 2012-05-06
  • 2011-11-07
  • 1970-01-01
  • 2016-07-02
相关资源
最近更新 更多