1

I'm just wondering if you could help me fix this issue I'm having with assigning an interface from my json file. I am getting the ts error of json file is not assignable to type Data. 'data' is declared as a type of Data in the .ts file.

  this.data = '../assets/data.json';

  export interface Data {
      millers: Miller[];
  }

  export interface Miller {
      name: string;
      address: string;
      farms: Farm[];
  }

  export interface Farm {
     code: string;
     name: string;
     harvest: string;
     type: string;
     paddocks: Paddock[];
  }

  export interface Paddock {
     code: string;
     area: string;
     owner: string;
  }


  {
  "millers": [
    {
      "name": "Britney Houston",
      "address": "Summit Street Haena",
      "farms": [
        {
          "code": "deserunt840",
          "name": "Artiq",
          "harvest": "2012-06-26",
          "type": "Cane",
          "paddocks": [
            {
              "code": "do318",
              "area": 965
            },
jmckie
  • 241
  • 4
  • 11

2 Answers2

1

EDIT:

You can read JSON file using requirejs. Check this question for more details: Angular 5 Service to read local .json file.


this.data = '../assets/data.json';

This is your issue. All you're doing on this line assigning a String value to this.data. And as you mentioned this.data is of type Data, not string. Hence the error

Now, coming back to your issue, you cannot read data from JSON file (As far as I know.). If you have to, convert that JSON file into a .ts file and export your data from that file. then you can import it and assign to this.data or any other property

Manish Gharat
  • 400
  • 1
  • 10
1

As commented you're assigning a string value to a property that you've declared of type Data.

To fix it:

  1. Make sure you have the following in architect.build.options in angular.json:

"assets": [
  "src/favicon.ico",
  "src/assets",
],
  1. Create a millers.json file in src/assets.
  2. Import HttpClientModule in your Module and add it to the imports array.
  3. Inject HttpClient as a dependency in your Component and then use it's get method to call the .json which is sort of exposed as an API file:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({...})
export class AppComponent {
  data;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('../assets/millers.json')
      .subscribe(res => console.log(res));
  }
}

HEre's a Sample StackBlitz for your ref.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110