Home > Software design >  error TS2740 on Angular when trying to load .json
error TS2740 on Angular when trying to load .json

Time:02-18

I am a novice in Angular/Typescript and I am trying to build a dynamic page with the champion_info.json in order to display all the data in a list. I tried to upload the data from my json file but I have this error and I don't know what to do about it. I watched every possible youtube video about this subject but I still can't find an answer.

How can I simply load my data from the .json file and use it in order to display it in a list ?

This is my hero.component.ts :

import { Component, OnInit } from '@angular/core';
import * as Heroes from "src/hero_json/champion_info.json";

interface heroes1 {
  title: String;
  id: Number;
  name: String;
  key:String;
}

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
  liste !: heroes1 = Heroes;

  constructor() {
    
  }

  ngOnInit(): void {
  }
    
}

This is the error

And this is where you can find the champion_info.json file: https://www.kaggle.com/datasnaek/league-of-legends?select=champion_info.json

CodePudding user response:

First, as you have indicated above you need to get .data from the JSON object, in your component class:

heroes = json_data.data;  

In your template use the angular keyvalue pipe to parse and display data where you have a list of objects rather than an array.

<div *ngFor="let hero of heroes | keyvalue">
  {{ hero.value.title }}
  {{ hero.value.name }}
  // etc
</div>

CodePudding user response:

Probably the problem is you need to add

declare module "*.json" {
   const value: any;
   export default value;
}

in a file in the app folder as

json-typings.d.ts

Anyways here is the repo I create to answer your question with basic and complete way to build this app you can clone a try to u

repor basic app

  • Related