2017-05-25 64 views
1

問題: 具有值的常量變量模型數組正在變爲沒有任何直接變化的變量。Angular 2不能讓模型對象的json常量

我的模式是:

export class Section { 

    sectionId : string; 
    sectionLabel : string; 
    sectionIcon : string; 
    sectionComponents : Array<SectionComponent>; 
} 

現在我要宣佈這個模型,它必須是恆定的,在無處不在項目的一個默認數組變量

這個模型合適JSON是:

SECTIONS_CONST: Section[] = [ 

      { 
      sectionId: 'testId', 
      sectionLabel: 'testLabel', 
      sectionIcon : 'testIcon', 
      sectionComponents : [ 
         { 
         sectionComponentId : 'testSectionComponentId', 
         label : 'test label', 
         inputModels : [ 
          { 
          inputName : 'testName', 
          model : '' 
          } 
          ], 
         componentBasedData : null, 
         selectedQuerys : [] 
         } 
       ] 
      } 
] 

注意:這個數組在我的代碼中正常工作,但唯一的問題是,在這個數組中沒有任何值必須改變任何方式。

我嘗試過很多辦法如下:

  • 提出這一變量私有類和getter方法返回該變量的值
  • 出口這一變量恆定
  • 嘗試Object.assign ({},yourObject);
  • 嘗試Object.freeze()
  • 嘗試_.cloneDeep()

還有更多的東西我試過了。

仍試圖用不同的解決方案,但無法獲得任何工作。

+0

你是說'SECTIONS_CONST'以某種方式改變,你不希望它改變嗎? – Huangism

+0

你嘗試過'Immutable.js'庫嗎? – AngJobs

+0

是@黃色。我不想改變這個變量的值。 –

回答

3

你看過ReadonlyArrayconst嗎?

const SECTIONS_CONST: ReadonlyArray<Section> = ... 

隨着ReadonlyArray,你將無法添加或更改項目:

// Not allowed 
SECTIONS_CONST.push(...); 
SECTIONS_CONST[0] = ... 

而且const防止再分配:

// Not allowed 
SECTIONS_CONST = []; 

但是你仍然可以改變現有的屬性item:

SECTIONS_CONST[0].sectionId = null; 

所以,你可能想使Section屬性只讀太:

export class Section { 
    readonly sectionId : string; 
    // etc 
} 

// Not allowed 
SECTIONS_CONST[0].sectionId = null;