Guide to retrieving JSON data from a JSON file using Angular 4

In the midst of a project, I found myself in need of a JSON file stored within an assets folder. To accomplish this, I created a service and component. 1- The JSON file resides in the assets folder.

data.json

[ 
 {
    "Date" : "10/09/2017",
    "ID" : "1",
    "Color" : "Orange",
  }, {
    "Date" : "10/11/2017",
    "ID" : "2",
    "Color" : "Green",
  }
]

To access and store the data in JSON format, I developed a service that retrieves the data from the JSON file in the assets folder. This setup ensures easy accessibility to the JSON file.

data.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class DataService {

  constructor(private http: Http) {   }

  fetchData() {
    return this.http.get('assets/data/data.json').map(
      (Response)=>Response.json()
    ).subscribe(
      (data) => {
        console.log(data);
      }

    );
  }

}

The service functions as intended, displaying the JSON data in the console. Moving on to the

data.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../../services/data.service';
import { DataTablesModule } from 'angular-datatables';

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

  constructor(private DataResponse: DataService ) { }

  ngOnInit() {
    this.DataResponse.fetchData();
  }

}

While the JSON data is successfully displayed in the console, I encountered difficulties when attempting to display it in HTML. Various approaches were explored but none yielded the desired outcome.

I will continue trying to find a solution and update this question accordingly. Any assistance in resolving this matter would be greatly appreciated.

Answer №1

Instead of enrolling in the subscription service, consider subscribing within the component. Have the service return the observable.

 fetchData() {
    return this.http.get('assets/data/data.json').map(
      (Response)=>Response.json()
    )
  }

Next, subscribe within the component and connect the data variable to the HTML elements.

export class DataComponent implements OnInit {
  data:any;

  constructor(private DataResponse: DataService ) { }

  ngOnInit() {
    this.DataResponse.fetchData().subscribe(
      (data) => {
       this.data = data;
      }

     );
    };
  }

}

Answer №2

The JSON data provided is in an invalid format. It seems that there are trailing commas in the last items, which is not allowed in JSON arrays and objects.

It should look like this:

[ 
 {
    "Date" : "10/09/2017",
    "ID" : "1",
    "Color" : "Orange"
  }, {
    "Date" : "10/11/2017",
    "ID" : "2",
    "Color" : "Green"
  }
]

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

triggering a function from a child component in React

I am facing a challenge in calling a function from the parent component that is stored in a child component. I understand how to do it from child to parent using props, but unsure about how to achieve it from parent to child. In the example below, you can ...

Is there a way to send me the result of the radio input (Yes/No) via email?

Is it feasible to send the results of a radio input (Yes/No) back to my email directly using HTML, CSS, and Javascript? ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Expand a simple object containing an array of simple objects into a single, flat object

update: The issue was incorrectly described at first. I have completely rewritten the description, along with sharing a code snippet that may not be aesthetically pleasing but gets the job done to some extent. Imagining an object: const input = { a: 1, ...

Express Session doesn't remove the variable assigned

While developing a web application using Node Express, I encountered a simple issue in my new project. Despite setting a session variable to null, the old session data is still being called. Seeking assistance to resolve this issue. I utilized express-ses ...

org.codehaus.jackson.map.JsonMappingException: Unable to locate a serializer for the specific class org.apache.struts.action.ActionServletWrapper

Exploring the potential workload required for migrating our older Struts 1.x web application to AngularJS + Java RESTful Web Service is on my agenda. Admittedly, Struts 1.x doesn't seamlessly integrate with AngularJS. One key challenge I've enco ...

Issue with MVC and three.js

Currently, I have a three.js code that enables me to develop a virtual tour. I am looking to incorporate an MVC approach, but I am encountering an error that I am struggling to resolve. Below is the code I have: Scene.js import * as THREE from 'thre ...

Using Knockoutjs to fetch and display server-side data within the MVC framework

My goal is to initialize my knockoutjs viewmodel with data from the server. In my ASP.Net MVC project, I achieve this by passing a mvc viewmodel to the view: public ActionResult Edit(int cvId) { CV cv = repository.FindCV(cvId); //auto mapper mapp ...

Is there a way to modify node attributes in the tick function of a d3 force-directed graph?

When working with a force directed graph, I am tasked with creating either circle or square nodes based on the group they belong to. The node creation process involves: const node = svg .append('g') .attr('stroke', &apo ...

I noticed that on my checkout sections, the toggle feature causes them to fold up and then immediately fold back down. This behavior should only happen

Is there a way to make my checkout sections fold up once instead of folding up and down when using toggle? I have created a test case in jsfiddle: (no styling done yet!) http://jsfiddle.net/Wd8Ty/ The code responsible for the behavior is located in AMLRW ...

Error encountered when attempting to send a request with two parameters to a service due to a NULL

Looking for assistance with sending two objects from Postman to a Spring Boot application service and encountering an internal server error. Here is the response: { "timestamp": 1585855140707, "status": 500, "error": "Internal Server Error", ...

Ways to distinguish a type that may not have a defined value

What is the most effective method to define an interface that may be undefined? Currently, I have the following setup but I am seeking a more sophisticated and succinct alternative. interface RouteInterface { path: string; test: boolean; } type TypeOr ...

Changing the value of HTML elements from Node.js is not allowed

I am facing a challenge with an HTML form that requires user input. Once the form is completed, the data entered needs to be validated to ensure that the username provided is unique. If the username is not unique, I need to reload the sign-up page (signUp. ...

Error message: "The getJSON call is missing a semicolon before the statement."

Can someone please explain the following. I've been searching online for a long time trying to find assistance and I think I am following all the correct steps but still receiving errors. Here is the script in question on my webpage: function GetPag ...

Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList. https://i.stack.imgur.com/rFlM2.png I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an ...

HighStock chart malfunctioning with inaccurate epoch datetime display

I am working on a project that involves creating a dynamic Highstock chart to showcase the daily influx of emails. The data is stored in a JSON file that gets updated every day, and you can see a snippet of it below: [{ "name": "Month", "data": [147199320 ...

What is the process of connecting React child and parent components when initializing them?

I am working with two nested components, TopBarItem and Menu, that have a specific functionality: "if the menu is open, the top bar should not display the tooltip". I want to connect them together using the following code: <TopBarItem tooltip="Settings ...

Incorporate Monaco Editor into an AngularJS 1.X project

Due to the challenges presented in this particular issue, I am seeking an alternative JavaScript-based source code editor compatible with AngularJS 1.X. My current exploration has led me to consider utilizing Monaco Editor. While I have successfully execu ...

Having trouble with enzyme in React Typescript application

One of my components is called app.tsx import React, { useState } from "react"; const TestComponent = () => { return( <> <div className="head">hey there</div> <select name="xyz" id=&qu ...

What is the best way to pass multiple variables to a PHP file with AJAX using a GET request?

Can you help me figure out how to send both an I.D. value and a name value to a php file using ajax? Currently, I am successfully sending just the I.D. variable, however, when I attempt to add the name variable, the function stops working. The code that w ...