Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON array from local file to Typescript array in Angular 5

I am using Angular 5 to develop a web app. I have JSON file which looks like this:

[
  {
        "id": 0,
        "title": "Some title"
  },
  {
        "id": 1,
        "title": "Some title"
  },
  ...
]

This file is stored locally. I also have an interface:

export interface Book {
  id: number;
  title: string;
}

The questions are how do I:

  1. Fetch the data from the file?
  2. Create an array of type Book[] from this data?
like image 259
Nikita Marinosyan Avatar asked Feb 14 '18 22:02

Nikita Marinosyan


2 Answers

You could load the file with import:

import data from 'path/to/data.json';

And assign that to an array of type Book[]:

@Component({...})
class Foo {
   books: Book[] = data;
}

demo

Also add a wildcard module definition in src/typings.d.ts to tell the TypeScript compiler how to import *.json:

declare module "*.json" {
  const value: any;
  export default value;
}
like image 107
tony19 Avatar answered Nov 06 '22 21:11

tony19


This answer could help someone, although it pertains to Typescript 4.(Angular 5 supports Typescript 2 ).

The sample JSON file content (data.json):

[
  {
    "Gender": "Male",
    "HeightCm": 171,
    "WeightKg": 96
  },
  {
    "Gender": "Male",
    "HeightCm": 161,
    "WeightKg": 85
  }
]

Appropriate tsconfig.json entry:

{
    "compilerOptions": {  
      "esModuleInterop": true
      "resolveJsonModule": true
    } 
}

The code that reads the JSON content into an interface Person:

import data from './data.json';

interface Person{
    Gender: string,
    HeightCm: number,
    WeightKg: number
}

const personArray:Person[] = data as Person[];
like image 41
Binita Bharati Avatar answered Nov 06 '22 20:11

Binita Bharati