我有一个简单的服务来更新对象。我深度克隆初始对象并更新克隆对象。
正如您所看到的,它运行良好,但 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/