What are the ways to integrate JSON data into Angular?

I am facing some issues with integrating JSON in Angular.

Within my project, I am generating components and deleting the spec.ts files.

Subsequently, I create a new file called prod.data.json

{
    "products" :
        [
            {
                "sku" : "10",
                "name" : "Laptop Blue Background",
                "saleTag" : false,
                "prodImage" : "img",
                "price" : "210",
                "discountly" : "200",
                "revives" : "3",
                "summary" : "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only",
                "availability" : "In Stock",
                "categori" : "Business",
                "tag" : "Book",
                "share" : {
                        "facebook" : "link",
                        "twitter" : "link",
                        "instagram" : "link",
                        "linkedin" : "link"
                },

The JSON code follows this format.

The file content.companents.ts consists of the following codes:

import prodData from '/Users/obasekin/angular-crash/src/app/prod.data.json';
interface Product {
  sku: Number;
  name: String;
  saleTag: String;
  prodImage: String;
  price: Number;
  discountly: Number;
  revives: Number;
  summary: String;
  availability: String;
  catagori: String;
  tag: String;
  share: {
    facebook: String;
    twitter: String;
    instagram: String;
    linkedin: String;
  };
  description: {
    desSummary: String;
    desList: {
      lineMono: String;
      lineDi: String;
      lineTri: String;
      lineTetra: String;
      linePenta: String;
      lineHexa: String;
    };
  };
}

I am importing the format as either String or Number.

The issue lies within this code:

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {

  constructor() { }

  products: Product[] = prodData;
  
  ngOnInit(): void {
  }

}

The problem occurs in this line:

products: Product[] = prodData;

The issue is as follows:

Click here for more details

Update 1

I have included the tsconfig.json file:

"resolveJsonModule": true,
"esModuleInterop": true

Alternatively, another problem persists:

See more details here

Regards

Answer №1

The values in your prod.data.json file were incorrectly set as strings instead of numbers.

To correct this, update the values as shown below:

{
  "products": [
    {
      "sku" : 10,
      "name" : "Laptop Blue Background",
      "saleTag" : false,
      "prodImage" : "img",
      "price" : 210,
      "discountly" : 200,
      "revives" : 3,
...

Answer №2

The reason for this issue is that the variable prodData is not an array; it's actually an object that contains an array of products.

To fix this problem, you need to introduce a wrapper object in your interface:

export interface Inventory {
  products: Product[];
}

export interface Product {
  ...
}

After defining the wrapper object, make the following changes in your class file:

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {

  constructor() { }

  inventory: Inventory = prodData;
  
  ngOnInit(): void {
  }

  get products(): Product[] {
    return this.inventory.products;
  }

}

Answer №3

I have just created a new file called:

content.interface.ts

Here is the content of the file:

export interface IProduct {
    sku: Number;
    name: String;
    saleTag: boolean;
    prodImage: String;
    price: Number;
    discountly: Number;
  }

Additionally, I created another file named:

content.components.ts

I imported both files and specified their paths as follows:

import prodData from '../(what was ur json file name).json';

import {IProduct} from './content.interface'

Lastly, I exported the class in the following way:

export class ContentComponent implements OnInit {
      products: IProduct[] = prodData.products;
}

Everything is now working perfectly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Any tips on how to convert a bincode serialized data into serde_json::Value?

I'm currently working on an IPC implementation where a process serializes a struct using bincode. However, on the receiving end, the process is unaware of the structure it's receiving. I want to achieve something similar to: let parsed: Result&l ...

The HTML element in the side menu is not adjusting its size to fit the parent content

Update: What a day! Forgot to save my work... Here is the functioning example. Thank you for any assistance. I have set up a demo here of the issue I'm facing. I am utilizing this menu as the foundation for a page I am developing. The menu is built ...

What is the correct way to type this object conversion?

I'm trying to ensure type safety for a specific converting scenario. The goal is to map over the palette object and convert any entries to key-value pairs, similar to how tailwindcss handles color configurations. However, I am facing an issue where th ...

Issue observed with alignment not being corrected when the browser is resized on a responsive webpage

Utilizing Bootstrap3 for my responsive page design. In the banner content, I am including a box with text inside: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/> <div class="row"> <s ...

Swap out the div element with a loading.gif image right before the page finishes loading, then pause for 3 seconds before getting rid of

My challenge involves a select drop down that is being dynamically built. To handle this, I have implemented a setTimeout function to change the selected option after a 3-second delay. This allows the select element to load first before I manipulate it. Ho ...

How can I convert JSON data to a List of classes and vice versa?

Hey everyone, I'm having trouble getting this to work. I checked on SO and thought I found a solution, but it's not working for me. Error message: The deserialized type should be a standard .NET type (not a primitive type like integer, nor a ...

The challenge of styling React components

Starting a new project with React and Redux has presented me with the challenge of deciding on a styling method. As a newcomer to React, I want to choose a method that won't compromise performance, will offer all CSS3 features, and is easy to maintain ...

Using PHP's mysqli function to generate a JSON array

Currently, I am in the process of learning php/mysql to enhance a website that I am constructing. Initially, everything was functioning as intended but there were numerous vulnerabilities and security flaws with minimal error handling mechanisms. To addres ...

css background-size and image position not working

On my website, users/members can upload or link a custom image for the start page. This feature works well with modern browsers that support background-size in CSS. However, if the browser does not support css3 background-size, the image may not fill the e ...

Using a single TypeORM connection across various modules in NestJS

In the process of developing a link shortener, I have set up a CRUD REST API for authentication and creating shortened links. Now, I am looking to manage redirects for these shortened URLs without using the same path as my API endpoints (e.g. /api/v1/). Af ...

Fetch the Future<list<DATA>> array from an API in Flutter and parse the JSON response

I recently dove into Flutter and decided to start using FlutKit packages. I've encountered a challenge with an array LIST while working on this project. FlutKit utilizes a list with static Json data to cache initial data, including Products, Categorie ...

Divide the page vertically. On the left side, feature an eye-catching image, while on the right side,

While I have a good understanding of bootstrap 5, I am currently working on a project that requires me to split the page down the center. However, I also need to incorporate a container in the middle that sets a boundary for the text so it doesn't exp ...

Communication between React.js and Node.js in VS Code

I recently started learning React and node js. I managed to create a simple "Hello World" project in reactjs, which works perfectly. App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.cs ...

Overlapping agendas within Microsoft Planner

A request needs to be made to POST v1.0/groups with the following JSON body: { "description": "hello", "displayName": "group_for_restore", "groupTypes": [ "Unified" ], "mailEnabled": true, "mailNickname": "group_for_re ...

Converting a JSON Response to a Pandas Dataframe

I am attempting to retrieve an API response from and convert it into a Pandas Dataframe. Specifically, my goal is to extract the 'Points' array and load it into the data frame. I have tried using json_normalize as suggested in other posts, but a ...

Aligment issues in columns on Bootstrap 5

I currently have a layout using Bootstrap 5 with multiple rows and columns. My goal is to have the columns aligned within each row, but I am experiencing issues where some borders are not lining up correctly with the columns. .VI-border { border-t ...

Issue with loading scripts in CodeIgniter, jQuery Mobile, and jQuery UI - scripts are not loading initially, requires a refresh to

I am currently facing issues with my codeigniter application. The problem arises when I have a view/form (view 1) that, upon submission, loads another view (view 2). When view 1 is initially loaded, it does not load the correct JavaScript and CSS. Instead ...

The IntrinsicAttributes type does not contain a property called 'theme'

As a junior TypeScript developer, I am exploring the creation of a dark mode feature using styled-components and a custom hook in TypeScript. useDarkMode.tsx import { useState } from 'react'; export const useDarkMode = () => { const [theme ...

Error TS2322: You cannot assign a Promise<any> to a string type

Having an issue in my react app where I am attempting to import the img source but encountering an error: TS2322: Type 'Promise<any>' is not assignable to type 'string'. What is the correct way to import an element into a variabl ...

Assistance needed for disabled JavaScript

I'm currently working on a small application where I need to display some text wrapped in 3 divs. The goal is to only show one div at a time and provide users with prev and next buttons to switch between them. However, when JavaScript is disabled, I w ...