简体   繁体   English

角度6变化检测-ngOnChanges不触发深层嵌套对象

[英]angular 6 change detection - ngOnChanges not firing for a deep nested object

I am having an object as below 我有一个物体如下

result =   [{
        "name": "jmd",
        "children": [
          {
            "name": "ppp1",
            "children": [
              {
                "name": "feeder",
                "children": [
                  {
                    "name": "rmu1",
                    "children": [
                      {
                        "name": "IT1",
                        "children": [
                          {
                            "aname": "Asset123",
                            "value" : "233"   
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }]

I need to detect the change every time the value changes using ngOnchanges event of Angular 6 . 每当使用Angular 6 ngOnchanges事件更改值时,我都需要检测更改。

it seems the angular ngOnchanges doesn't detect the deeply nested object.I have tried different things like 角度ngOnchanges似乎无法检测到深度嵌套的对象。

this.chartData = Object.assign({}, result);
this.chartData = {...result};

Nothing is working, any help would be appreciated :) 什么都没用,任何帮助将不胜感激:)

this.chartData = Object.assign({}, result);
this.chartData = {...result};

this doesn't clone the whole object, it only changes the top-root object, so for example if you have an object like this 这不会克隆整个对象,它只会更改根目录对象,例如,如果您有一个像这样的对象

var car = {
 model :"bmw",
 wheel:{
  type:"rounded",
  color:"black"
 }
}

and you use assign 你用assign

let anotherCar = {...car} //or Object.assign it's almost same)

the car object will be new, but the wheel object will be the same, and car and anotherCar will reference to the same object, sou you have to make deep clone, the easiest way right now is using JSON methods car对象将是新的,但是wheel对象将是相同的,而car和anotherCar将引用相同的对象,因此您必须进行深度克隆,现在最简单的方法是使用JSON方法

var newCar = JSON.parse(JSON.stringify(car)); // it will create whole new object

A quick note about Object.assign() and {...obj} object copying: both of them make a shallow copy of an object meaning that only own top-level properties will be copied. 关于Object.assign(){...obj}对象复制的快速说明:它们都对对象进行浅表复制,这意味着将仅复制自己的顶级属性

An example: 一个例子:

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

The code above shows that nested objects will not be cloned . 上面的代码显示了不会克隆 嵌套对象。 To make your code work correctly make a deep clone manually: {...a, b: {...source.b}} or use lodash 's _.cloneDeep(source) 为了使您的代码正常工作,请手动进行深层克隆: {...a, b: {...source.b}} lodash {...a, b: {...source.b}}或使用lodash_.cloneDeep(source)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM