Obtaining data from a Nested Json file in Angular 5

Encountering difficulties retrieving data from nested JSON.

Error: 
1. <h3>{{sampledata}}</h3> displaying [object Object]
   2. <p>{{sampleDataModel.Title}}</p> ERROR TypeError: Cannot read property 'Title' of undefined

Directory Structure:

sampledata.json:

{
    "isSuccessfull": true,
    "Model": [
        {
            "SampleDataModel": [ 
                {
                    "Title": "SampleData 1",
                    "Description": "Some Text"
                }
            ],

            "SampleDetailModel": [
                {
                    "Name": "Donald Trump",
                    "Id": "111",
                    "Country": "USA"
                }
            ]
        }
    ]
}

sampledata.services.ts :

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class SampledataService {

private _url = 'assets/data/sampledata.json'

constructor(private _http: Http) { }

getData(){
return this._http.get(this._url)
.map((resSampleData: Response) => resSampleData.json());
}

}

sampledata.component.ts:

import { Component, OnInit } from '@angular/core';
import { SampledataService } from '../sampledata.service'

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

sampledata = [];
sampleDataModel = [];
sampleDetailModel = [];

constructor(private _sampledataservice: SampledataService) { }

ngOnInit() {
this._sampledataservice.getData()
.subscribe(resData => { 
    this.sampledata = resData;
    this.sampleDataModel = resData.Model.SampleDataModel;
    this.sampleDetailModel = resData.Model.SampleDetailModel });
}

}

sampledata.component.html:

<h3>{{sampledata}}</h3>
<p>{{sampleDataModel.Title}}</p>

app.module.ts:

 declarations: [
AppComponent,
SampledataComponent
],
imports: [
BrowserModule, HttpClientModule, HttpModule
],
providers: [HttpClientModule, SampledataService],

angular-cli.json:

"assets": [
"assets",
"assets/data/sampledata.json",
"favicon.ico"
],

Seeking Assistance On:

  1. How can I display these values on sampledata.component.html,

sampledata and sampleDataModel.Title?

If anyone has suggestions or solutions to resolve this issue, please feel free to share. Thank you.

Answer №1

It appears that the problem lies within this line of code:

private _url = 'assets/sampledatajson'

To resolve this issue, make sure to add a dot . before json as shown below

private _url = 'assets/sampledata.json'

Answer №2

Ensure that in your sampledata.component.html, you correctly bind the variable to sampledata instead of sampledataModel. This is important because within the subscribe function, values are assigned to this.sampledata.

Answer №3

Take a close look at your JSON structure to pinpoint the location of your properties... You can retrieve the desired data using the following code:

this.sampledata = resData;
this.sampleDataModel = resData.Model[0].SampleDataModel[0];
this.sampleDetailModel = resData.Model[0].SampleDetailModel[0];

If you want to display sampleData directly without iteration, use the json pipe like this:

<pre>{{sampledata | json}}</pre>
<p>{{sampleDataModel?.Title}}</p>

Furthermore, ensure that all your variables are objects by initializing them as empty objects rather than arrays, as shown below:

sampledata = {};
sampleDataModel = {};
sampleDetailModel = {};

View StackBlitz Example

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

a guide on transforming a string array into JSON

I initialized an array like this String[] finalcodes = new String[50] ; and populated it with some values. However, when I print finalcodes, the output is: ["aaa","bbb","ccc"] My goal is to convert this string array into a JSON Object. Can someone pl ...

What methods can be used to authenticate the user's input?

I am facing an issue with my program where it breaks if there is a space behind the last number entered. I want to prevent the function from breaking when a space is entered. I tried using $.trim but couldn't get it to work. I also attempted using an ...

Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently. I have 2 JSON files: images.json { "imageName": "example.jpg", "imageTags": ["fun","work","utility" ...

What is the most efficient method for integrating third-party components just once in an Angular 8 application?

Is there a preferred method for configuring 3rd party components? I frequently use primeng p-table in various components throughout my application. I am looking to configure it globally for the entire application - enabling the paginator by default, setti ...

What is preventing this from being passed to the subsequent component in ReactJS?

I am trying to get the Portfolio class to utilize the this.prompt method from the Title Bar class. Despite extensive research, I have not been able to find a definitive solution for this yet. Currently, my screen is just blank. Below is the content of my ...

The object does not have a property named 'fetch' and therefore cannot be read

Struggling to integrate a REST datasource into my Apollo Server. I've created a class that extends RESTDataSource for handling API requests. However, when attempting to call the login method from my GraphQL resolver code, an error is being thrown. An ...

Exploring a collection of objects housed in a json document

Currently, I'm looking to retrieve a collection of objects using JavaScript from a JSON file that resides on my website. While I could easily embed the array of objects directly into my JavaScript code, I am interested in understanding how to work wit ...

Replacements of JSON null values within Mantle

Utilizing Mantle for parsing JSON data, the typical structure includes: "fields": { "foobar": 41 } However, there are instances where the value of foobar is null: "fields": { "foobar": null } This leads to an exception being thrown ...

Triggering an event within a component to execute a specific function in another component

I am working on a component that includes multiple routes such as home, app, and navbar. My goal is to have the encrementcalc() function execute when the navbar button is pressed. I attempted to use the event emitter but was unsuccessful. Can someone prov ...

Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append f ...

List of coordinates extracted from PolylineMeasure plugin in the React Leaflet library

I have 3 different scripts: 1. PolylineMeasure.jsx import { MapControl, withLeaflet } from "react-leaflet"; import * as L from "leaflet"; class PolylineMeasure extends MapControl { createLeafletElement() { return L.control.poly ...

Tips for retrieving the text from a child element in a list with jQuery

I'm having trouble accessing the text of a child element within a list. I can only access the parent element and not sure how to get to the child element. Here is the HTML code: <ul class="nav nav-list"> <li class="active"> < ...

We are experiencing an issue with WebSQL: The number of placeholders in the statement does not match the number of arguments provided

I'm looking to develop a customized function for dynamically inserting data into the webSQL Database. Unfortunately, indexed DB is not an option due to Zetakey's lack of support for it. tx.executeSql("INSERT INTO " + table + "(" + formatfields ...

Convert your Airbnb short link into the full link

I am currently developing an application that utilizes Airbnb links as part of its input. So far, I have identified two types of links: Long form, for example: . These are commonly used on desktop. Short form, such as: . These shorter links are often shar ...

When dynamically loaded HTML is involved, Javascript ajax calls often fail to execute properly

Currently, I am in the process of creating a JavaScript script that can facilitate clicking through <a href> links by only replacing the inner HTML instead of reloading the entire page. The interesting thing is, it seems to be functioning properly, e ...

Event triggered when a text input field becomes active (excluding onfocus) in the FireFox browser

I'm currently working on detecting when a text input field is active. Initially, I used the onfocus event, but I encountered an issue where the onblur event would be triggered when the window was no longer in focus, causing unintended consequences in ...

Numerous unresolved peer dependency issues have been detected, such as a missing @angular/[email protected]

I've been encountering issues with package dependencies lately, specifically related to angular2-busy. However, upon further investigation, it seems like there may be a larger underlying problem. Whenever I execute "npm list", I am bombarded with UNM ...

The useForm function from react-hook-form is triggered each time a page is routed in Nextjs

Hey there, I'm just starting out with Next.js (v14) and I'm trying to create a multi-page form using react-hook-form. But I'm encountering an issue where the useForm function is being executed every time, and the defaultValues are being set ...

The `setState` function is failing to change the current value

I'm having an issue with setting State in the dropdown component of semantic-ui-react while using TypeScript in my code. The selected category value is always returning an empty string "". Any suggestions on how to resolve this problem? impo ...

Replacing the resetPose function in webVR

I'm currently working on a webVR project where I previously used the resetPose function to reset the origin of the scene. However, it seems that this function is now deprecated. The purpose of using it was to bring the camera back to focusing on the c ...