简体   繁体   中英

How to create new recursive json object from interface in Angular 8

I am trying to create a Json with the following format

{
  "via": [
    {
      "name": "Kittin",
      "vagon": [
        {"id":123},
        {"id":321}
        ]
    }
  ]
}

I use the following interface

app.interface.ts

interface RootObject {
  via: Via[];
}

interface Via {
  name: string;
  vagon: Vagon[];
}

interface Vagon {
  id: number;
}

But trying to use it returns the following error

app.component.ts

varData: IVias;

this.varData.via.push('foo');

// this.varData.via = 'foo';

core.js:6014 ERROR TypeError: Cannot read property 'via' of undefined

Thanks in advance for the help

As the message says, varData is undefined.

Probably because it's not initialized at the beginning of your script.

A simple fix would be:

this.varData = { 
   via : [],
}

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