Home > Software design >  Getting error in accessing Interface in Angular
Getting error in accessing Interface in Angular

Time:02-16

I am trying my best but getting error of type in accessing the data. Help needed.

I have a json as below

[{
  "productType": "Electronics",
  "modelDetails": [
    {
      "modelId": "I Kall K 48",
      "modelPrice": 759,
      "specifications": {
        "memory": "32 MB RAM | 64 MB ROM",
        "display": "4.57 cm (1.8 inch) Display",
      }
    }, 
    {
      "modelId": "I Kall K 48",
      "modelPrice": 759,
      "specifications": {
        "memory": "32 MB RAM | 64 MB ROM",
        "display": "4.57 cm (1.8 inch) Display",
      }
    }
  ]
}]

Below is my ts file with defined Interface.

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

import productsData from './jsonFile3.json';

interface Product {
    productType: String,
    modelDetails: ModelDetails
}

interface ModelDetails {
    modelId: String,
    modelPrice: Number,
    specifications:Specifications
}

interface Specifications {
  memory: String,
  display: String,
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  title = 'ngapplication';
  name = 'Angular';
  products: Product[] = productsData;
}

I am getting error as

error TS2322: Type '{ productType: string; modelDetails: { modelId: string; modelPrice: number; specifications: { memory: string; display: string; }; }[]; }; }[]' is not assignable to type 'Product[]'.

Also, if there is only single data in modelDetails then it is captured but when it becomes an array of object then even after declaring modelDetails: ModelDetails[], still it is not rendered.

Can anyone help me out in this ??

Thanks

CodePudding user response:

You need to define like;

interface Product {
    productType: String,
    modelDetails: ModelDetails[]
}

Because in JSON your ModelDetails is an array.

CodePudding user response:

Here 'productsData' you are accessing is the object and you are directly trying to assign it to array based variable 'products'. thats why it shows you error. I think you should push 'productsData' as element of array like array.push(productsData). at least try it.

  • Related