Javascript 克隆对象和更新视图
我有一个简单的服务来更新一个对象。我深度克隆初始对象并更新克隆对象 如您所见,它运行良好,但视图未更新。如何更新更改视图 代码如下: 还有一个问题,如何修改Javascript 克隆对象和更新视图,javascript,angular,Javascript,Angular,我有一个简单的服务来更新一个对象。我深度克隆初始对象并更新克隆对象 如您所见,它运行良好,但视图未更新。如何更新更改视图 代码如下: 还有一个问题,如何修改number.three传递函数路径的值,如:“number.three”?:请回答: AppComponent import { Component, OnInit } from '@angular/core'; import { ObjectService } from './object.service'; @Component({
number.three
传递函数路径的值,如:“number.three”?:请回答:
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')
}
}
changeObject () {
this.object = 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>
{{object.one}
{{object.two}
{{object.number.three}
更改对象
您需要在变更对象中指定返回值
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')
}
}
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;
}
您可以使用
Object.assign()
深度克隆您的对象是的,我知道,但您也会遇到同样的问题。是的,很好,它正在工作。(您忘记更新stackblitz)。关于我的第二个问题?没关系,我在这里找到了答案: