Kroshandowski
Kroshandowski

Reputation: 81

How to read nested json array in Angular?

I have array from local json file test.json

{"collection":[{"scriptId":"28936862","startDate":"2020-03-31T15:54:45.658992","endDate":"2020-03-31T15:57:33.573312","createDate":"31.03.2020 15:54:45"}}]

So this is my app.component.ts

import { Component } from '@angular/core';
import tasksData from '../assets/test.json';

interface Task {  
  scriptId: String;  
}

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

export class AppComponent {      
  tasks: Task[] = tasksData;
}

This is my app.component.html

<div class="container">
 <table class="table table-striped">
   <thead>
    <tr>        
     <th>Name</th>        
    </tr>
  </thead>
 <tbody>
  <tr *ngFor="let task of tasks">
    <td>{{ task.scriptId }}</td>        
  </tr>
 </tbody>
</table>

The code above i took from here. In the example array is simple. But my array starts with "collection", and the code doesn't work.

My IDE gives an error on this line tasks: Task[] = tasksData;

How can I change the code for my json array?

Thank you in advance

Upvotes: 0

Views: 212

Answers (1)

lovis91
lovis91

Reputation: 2171

Define tasks property like this :

tasks: Task[] = tasksData.collection;

and your interface should be like :

interface Task {  
  scriptId: string;
  startDate: string;
  endDate: string;
  createDate: string;
}

Upvotes: 2

Related Questions