簡體   English   中英

角度6變化檢測-ngOnChanges不觸發深層嵌套對象

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM