简体   繁体   中英

How to access typescript interface property array?

If I have three interfaces like this:

registration-pivot.ts

export interface RegistrationPivot {
    THead: RegistrationPivotRow;
    TBody: RegistrationPivotRow[];
}

registration-pivot-row.ts

export interface RegistrationPivotRow {
    CellList: RegistrationPivotCel[];
}

registration-pivot-cel.ts

export interface RegistrationPivotCel {
    content: string;
}

Okay say now that I call a get API and put the object from the API to registrationPivot (also what do you call that: a property? a list? an empty object?):

registrationPivot: RegistrationPivot = {} as RegistrationPivot;

searchRegistrationStatistic(){
    this.registrationApi.getAllRegistrationStatistic().subscribe(res => {
    this.registrationPivot = res;
    });
}

In my html how do I get the values from the registrationPivot ?.

  • I tried doing registrationPivot.THead.CellList but that does not work.
  • Basically I have to loop through all the Cells inside the THead element (same with the TBody) but with the code I have I do not know ho to achieve it. Can someone please help me understand how to do it? Thanks!

Your interfaces and way of accessing data defined by such interfaces - are correct. As you can see in below example (I've run it in browser on JSFiddle ).

interface RegistrationPivotCel {
  content: string;
}

interface RegistrationPivotRow {
  CellList: RegistrationPivotCel[];
}

interface RegistrationPivot {
  THead: RegistrationPivotRow;
  TBody: RegistrationPivotRow[];
}

const example = {
    THead: {
    CellList: [
      {content: "title"}
    ]
  },
  TBody: [
    {
      CellList: [
        {content: "row A"},
        {content: "row B"}
      ]
    }
  ]
}

console.log(example.THead.CellList)
/*
[
  {
    "content": "title"
  }
]
*/

Probably data you are returning from this.registrationApi.getAllRegistrationStatistic() is not implementing these interfaces. Try even to console.log your res and see if this data is really implementing these interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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