[英]angular 6 change detection - ngOnChanges not firing for a deep nested object
我有一个物体如下
result = [{
"name": "jmd",
"children": [
{
"name": "ppp1",
"children": [
{
"name": "feeder",
"children": [
{
"name": "rmu1",
"children": [
{
"name": "IT1",
"children": [
{
"aname": "Asset123",
"value" : "233"
}
]
}
]
}
]
}
]
}]
每当使用Angular 6
ngOnchanges
事件更改值时,我都需要检测更改。
角度ngOnchanges
似乎无法检测到深度嵌套的对象。
this.chartData = Object.assign({}, result);
this.chartData = {...result};
什么都没用,任何帮助将不胜感激:)
this.chartData = Object.assign({}, result);
this.chartData = {...result};
这不会克隆整个对象,它只会更改根目录对象,例如,如果您有一个像这样的对象
var car = {
model :"bmw",
wheel:{
type:"rounded",
color:"black"
}
}
你用assign
let anotherCar = {...car} //or Object.assign it's almost same)
car对象将是新的,但是wheel对象将是相同的,而car和anotherCar将引用相同的对象,因此您必须进行深度克隆,现在最简单的方法是使用JSON方法
var newCar = JSON.parse(JSON.stringify(car)); // it will create whole new object
关于Object.assign()
和{...obj}
对象复制的快速说明:它们都对对象进行浅表复制,这意味着将仅复制自己的顶级属性 。
一个例子:
const obj = {a: 5};
const withNested = {b: 4, nested: obj};
const copy = {...withNested};
copy.nested === withNested.nested // outputs 'true' meaning the objects are the same and have not been copied
上面的代码显示了不会克隆 嵌套对象。 为了使您的代码正常工作,请手动进行深层克隆: {...a, b: {...source.b}}
lodash
{...a, b: {...source.b}}
或使用lodash
的_.cloneDeep(source)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.