Implementing Angular 4 to fetch information from a JSON file

As a beginner in Angular, my current task involves loading data from a JSON file upon click, which I have successfully achieved so far.

However, I am facing an issue where I'm unable to load the first JSON object before clicking, meaning that I want the first object to be loaded when the page initially loads.

Typescript

export class RequestComponent{
  people: Object[];
  constructor(http:Http){
    http.get('data.json').subscribe(res => {
      this.people = res.json();
    });
  }

  public currentStatus;
  public setThis = (people) => this.currentStatus = people;
}

Html

  <ul class="col-md-4">
    <li *ngFor="let person of people" (click)="setThis(person)">
      <span><i class="fa fa-cog" aria-hidden="true"></i></span>
      <p>{{ person.name }}</p>
    </li>
  </ul>
   <div *ngIf="currentStatus" class="col-md-8 right-section">
      <h2>{{ currentStatus.name }}</h2>
      <img [src]="currentStatus.img" class="img-responsive"/>
   </div>

Answer №1

Make sure to load the JSON data in the ngOnInit() function of your Angular component.

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

export class RequestComponent implements ngOnInit{
  people: Object[];

  constructor(private http:Http){}

  ngOnInit(){
      this.http.get('data.json').subscribe(res => {
      this.people = res.json();
    });
  }
}

Additionally, use ngIf to ensure that your records are only displayed after the 'people' data has been loaded.

<ul *ngIf="people" class="col-md-4">
    <li *ngFor="let person of people" (click)="setThis(person)">
        <span><i class="fa fa-cog" aria-hidden="true"></i></span>
        <p>{{ person.name }}</p>
    </li>
</ul>
<div *ngIf="currentStatus" class="col-md-8 right-section">
    <h2>{{ currentStatus.name }}</h2>
    <img [src]="currentStatus.img" class="img-responsive" />
</div>

Answer №2

It's important to ensure that your page loads quickly, especially in comparison to the response time from your API. One way to do this is by setting up your subscription inside the response function so you can be sure it has received the data.

constructor(private http:Http){
    this.http.get('data.json').subscribe(res => {
        this.people = res.json();
        if(this.people && this.people.length>0)
            this.setThis(this.people[0]);
    });
}

Depending on your specific implementation, you may want to consider adding a conditional check within the setThis function to ensure the people array is not empty before proceeding.


Another approach would be to update your HTML structure as follows:

<ul class="col-md-4">
    <li *ngFor="let person of people" (click)="setThis(person)">
        <span><i class="fa fa-cog" aria-hidden="true"></i></span>
        <p>{{ person.name }}</p>
    </li>
</ul>
<div *ngIf="currentStatus>-1" class="col-md-8 right-section">
    <h2>{{ people[currentStatus]?.name }}</h2>
    <img [src]="people[currentStatus]?.img" class="img-responsive"/>
</div>

Make sure to change currentStatus into a number and set its default value to 0. This adjustment allows for immediate updating of the HTML when there is at least one person in the array. To hide the currentStatus section, simply set it to -1. The use of '?' before accessing 'name' and 'img' ensures that the HTML checks if the object exists before displaying those values.

Answer №3

Here is a suggestion for you:

constructor(private http:Http){
    this.http.get('data.json').subscribe(res => {
        this.data = res.json();
    });
}

ngAfterViewInit(){        
    this.displayData(this.data[0]);
}

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

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

Troubleshooting Angular MIME problems with Microsoft Edge

I'm encountering a problem with Angular where after running ng serve and deploying on localhost, the page loads without any issues. However, when I use ng build and deploy remotely, I encounter a MIME error. Failed to load module script: Expected a ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

Automate your Excel tasks with Office Scripts: Calculate the total of values in a column depending on the criteria in another column

As a newcomer to TypeScript, I have set a goal for today - to calculate the total sum of cell values in one column of an Excel file based on values from another column. In my Excel spreadsheet, the calendar weeks are listed in column U and their correspon ...

Using AngularJS, I can bind the ng-model directive to asynchronously update and retrieve data from

I am currently working with Angular to develop a preferences page. Essentially, I have a field in a mysql table on my server which I want to connect my textbox to using ng-model through an asynchronous xhr request for setting and fetching data. I attempt ...

"Effortless Auto-complete with Linked Content and Visuals

I've been searching everywhere and have not been able to find a solution for this issue. I can successfully use JQuery Easyautocomplete () with links, and also with images separately, but I can't figure out how to make it work with both. I am new ...

What type of HTML tag does the MUI Autocomplete represent?

Having trouble calling a function to handle the onchange event on an autocomplete MUI element. I've tried using `e: React.ChangeEvent`, but I can't seem to locate the element for the autocomplete component as it throws this error: The type &apos ...

Error encountered: "Instance variable for Apex chart not defined while attempting to update charts with updateOptions."

I have integrated Apexcharts to create charts within my application. The initial data loads perfectly upon onload, but when applying a filter, I face an issue where the charts need to be refreshed or updated with the new filtered data. I attempted to use t ...

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

Can CSS be used to automatically focus on a div element?

Can CSS be used to set autofocus on a div element? <div class="form-group" style="margin-left:10px"> <label for="organizationContainer" class="nmc-label">@Res.GroupStrings.CreateNewGroupOrganization</label> <div id="organiza ...

Tips for sending the image file path to a React component

Hey, I'm working on a component that has the following structure: import React from "react"; interface CInterface { name: string; word: string; path: string; } export function C({ name, word, path }: CInterface) { return ( < ...

Optimizing Wordpress by Efficiently Enqueueing Javascript

As a beginner with a WordPress website, I am aware that in order to execute scripts on a WordPress page, they need to be enqueued in the functions.php file. However, I'm unsure about the correct process for this. The specific JavaScript file I want t ...

Attempting to compare the HTML datetime with the current time in order to implement conditional formatting

I am working with a SharePoint discussion list that includes a field named "Last Updated." My goal is to identify and highlight rows where the last update was more than 1 hour ago. Here is my current approach: <html> <head> <sc ...

Retrieve the total count of tables within a specific div element

If I have an unspecified amount of tables within a div, how can I determine the total number of tables using either plain JavaScript or jQuery? ...

What is the procedure for modifying the height of a button in HTML?

I wanted to add a flashing "Contact Us" button to the menu bar of my website to immediately attract people's attention when they visit. Here is the javascript code I used: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&g ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

Utilizing Angular 14 and Typescript to fetch JSON data through the URL property in an HTML

Is there a way to specify a local path to a JSON file in HTML, similar to how the src attribute works for an HTML img tag? Imagine something like this: <my-component data-source="localPath"> Here, localPath would point to a local JSON fil ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Issue with Bootstrap.js causing mobile menu to not expand when toggled in Rails app

Despite adding the .toggled class, my hamburger menu is not expanding when I click on the mobile menu. I've tried adjusting the order of the required javascript commands, but it doesn't seem to be working as expected. Here are the steps I'v ...