SerSergious
SerSergious

Reputation: 490

Nested Interface

I try to understand nested interfaces in Angular 5/TS and I can't reach any correct point. I created two interfaces:

export  interface Person {
    person: PersonData;
}

export interface PersonData {
    id: number;
    speed: number;
    weigth: number;

}

Also I mock a JSON server: https://www.jasonbase.com/things/VmaZ.json (see below).

{
  "person": [
    {
      "id": 1,
      "speed": 100,
      "weigth": 20
    },
    {
      "id": 2,
      "speed": 70,
      "weigth": 20
    },
    {
      "id": 4,
      "speed": 10,
      "weigth": 30
    }
  ]
}

And the questions is:

Upvotes: 2

Views: 785

Answers (2)

Gabriel Rodrigues
Gabriel Rodrigues

Reputation: 510

Simplify using only one interface, a good sample is:

export  interface Person {
    id: number;
    speed: number;
    weigth: number;
}

And in your component:

import { Component } from '@angular/core';

import { Person } from './person'; // get interface
import data from './person.mock.json'; // get mock

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  people: Person[] = data.person;
}

And loop like:

<ul>
  <li *ngFor="let person of people">
   id {{person.id}} | speed {{person.speed}}  | weight {{person.weigth}} 
  </li>
</ul>

Working example: StackBlitz

Upvotes: 2

Amit Chigadani
Amit Chigadani

Reputation: 29795

You dont need another interface just to hold the reference of PersonData

Person interface seems unnecessary, because you can simply create array of references pointing to PersonData interface.

let personData : PersonData[]

And then access them like personData[i].id or personData[i].speed

Upvotes: 2

Related Questions