【发布时间】: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