Facing challenges with parsing JSON files in an Angular 2+ application

Utilizing the Angular CLI, I have configured this project with the standard folder layout. My goal is to practice reading a JSON file from src/app/assets/items.json and then using it to display these items in the HTML.

items.json:

{
   "results": [
      "Item 1",
      "Item 2",
    ]
}

app.service.ts located in src/app/:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

// Importing required RxJs methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class AppService {
    private greetUrl = 'api/Hello';

    // HTTP resolved using constructor
    constructor(private _http: Http) { }

    findJSON(): Observable<any> {
        return this._http.get('assets/items.json').map((response: Response) => {
            return response.json();
        });
    }

    sayHello(): Observable<any> {
        return this._http.get(this.greetUrl).map((response: Response) => {
            return response.text();
        });
    }
}

and app.component.ts found in src/app:

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';

import { AppService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  greetings = '';
  itemsjson : string;

  constructor(private _appService: AppService) { }

  ngOnInit(): void {
    this._appService.findJSON()
      .subscribe(
      result => {
        this.itemsjson = result;
      }
      );
  }
} 

and app.component.html within src/app:

<html lang="en">
  <link rel="stylesheet" href="https://bootswatch.com/cerulean/bootstrap.min.css">
  <head>
    <meta charset="utf-8">
    <title>Yik-Yak Clone</title>
  </head>
  <body>
    <div class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <a href="../" class="navbar-brand">Yik-Yak Clone</a>
        </div>
      </div>      
    </div>

      <!-- Containers
      ================================================== -->
      <div class = "container">
        <div class="row">
          <div class="col-lg-12">
            <div class="bs-component">
              <div class="jumbotron">
                <h1>{{itemsjson}}</h1>
              </div>
            </div>
          </div>
        </div> 
      </div>

      <!-- Containers
      ================================================== -->
      <div class = "container">
        <div class="row">
          <div class="col-lg-12">
            <div class="bs-component">
              <div class="jumbotron">
                <h1>{{itemsjson}}</h1>
              </div>
            </div>
          </div>
        </div> 
      </div>

          <!-- 
      ================================================== -->
      <div class = "container">
        <div class="row">
          <div class="col-lg-12">
            <div class="bs-component">
              <div class="jumbotron">
                <h1>{{itemsjson}}</h1>
              </div>
            </div>
          </div>
        </div> 
      </div> 


  <nav class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
      <div class="navbar-head">
        <div class = "col-sm-3"></div>
        <div class="col-sm-6">
          <div class="form-group">
            <input class="form-control input-lg" type="text" id="inputLarge">
          </div>
        </div>
        <div class = "navbar-brand">
          <div class="col-sm-2">
            <div class="form-group">
              <button type="submit" class="btn btn-primary">greetings</button>
            </div>
          </div>
        </div>
        <div class = "col-sm-1"></div>
      </div>
    </div>
  </nav>

  </body>
</html>

Based on my research so far, everything seems to indicate that all components and logic are set up correctly.

Answer №1

If you want to iterate through the results property in your json data, you can use a ngFor loop.

<div class ="container" *ngFor="let item of itemsjson?.results">
    <div class="row">
        <div class="col-lg-12">
            <div class="bs-component">
                <div class="jumbotron">
                    <h1>{{item}}</h1>
                </div>
            </div>
        </div>
    </div> 
</div> 

The safe navigation operator (?) is used here because itemsjson may not be defined initially itemsjson?.results

Answer №2

You don't seem to be utilizing itemsjson anywhere in your HTML code. You might consider adding it like this:

<div class="jumbotron">
    <h1>{{itemsjson | json }}</h1> 
</div>

Answer №3

To begin, ensure to review your itemsjson using a console.log and then simply incorporate it into your template. If you wish to iterate through your data in a loop, utilize -

*ngFor='let data of itemsjson; let i = index' and include {{data}}
.

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

Display only the clear button within the p-calendar element

I am struggling to make a Clear button appear only on the p-calendar component. myComponent.html <p-calendar value="#{property.propDate}" id="date" [showIcon]="true" [utc]='true' placeholder="{{ timePickerPlaceHolder }}" [showTrans ...

Updating the email header for responding to New Order and shipped email notifications in Woocommerce

Looking for a solution to customize the reply-to email addresses specifically for New Order and Shipped emails sent to customers. I attempted to implement a suggested fix from this resource Change "reply to" email address in all Woocommerce email ...

SVG path tooltips are not functioning properly, unlike in regular HTML where they work perfectly

I have a CSS/HTML code that works perfectly in plain HTML and is also shown as an example at the end of the demo. However, it fails to work properly in SVG. Upon inspecting the element, I found that the :after code is being called but the tooltip remains ...

Tips on creating a blurred background effect when an HTML popup modal is activated

Whenever I click on a button, a popup window appears. What I want is for the background to be blurred when this popup modal opens. <div class="modal" id="myModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...

What is the best way to retrieve the previously chosen value from one dropdown and populate it into another dropdown when

I have 3 choices available. When the user selects the third option, a jQuery onchange event is triggered to send the variable to another PHP file for database validation based on the selected id. The challenge lies in how I can also include the variables f ...

Tips for confirming schedule accuracy

Trying to determine if a specific time falls between two others is the task at hand. Allow me to illustrate: Presently, it's Thursday, and the time reads 11:39 PM. Establishment X operates from 12:00 AM to 11:59 PM on Thursdays (a regular occurrence ...

What is the best way to display a child div without impacting the position of other elements within the same parent container?

As I work with a div html tag within a login form, encountering an error inside this form has presented a challenging issue. The error div sits at the top of its parent div, and ideally, upon activation, should remain within the form div without disrupting ...

Utilizing Typeface Styles in SCSS with the Latest Webpack Version 4

My Angular 6 SPA utilizes Webpack 4 for bundling, and I have encountered an issue while trying to import external fonts into the project. The project is based on the repository found at; AngularWebpackVisualStudio Example Repo After inspecting the webpac ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Differences between Pipe and Tap when working with ngxsWhen working with

While experimenting with pipe and subscribe methods, I encountered an issue. When using pipe with tap, nothing gets logged in the console. However, when I switch to using subscribe, it works perfectly. Can you help me figure out what I'm doing wrong? ...

Guide to Utilizing the Dracula Graph Library in Angular

Recently, I stumbled upon a JavaScript library that seems to be an ideal fit for my project. The library can be found at: After installing the necessary libraries using npm - npm i raphael graphdracula - new folders were created in node_modules and th ...

Unable to display menu content text using jQuery

Currently experimenting with jQuery to create a dynamic submenu. The goal is to have a sub menu appear when the main menu is clicked, and then disappear when an item in the sub menu is selected, revealing additional information within a div. Unfortunately, ...

A DIV element may not have any visible height, even when it contains content

My <div> contains multiple <img> elements, each wrapped in its own inner <div>. Despite setting the outer div's height to auto, it fails to adjust dynamically based on the content. To display the inner divs inline, I've applied ...

Encountering crashes while initializing the router in the constructor of a service in Angular 4.3

I've been scratching my head over this problem. It seems like I'm overlooking something simple. Let me show you what's inside my home.component.ts file: import { Component, OnInit } from '@angular/core'; import { AuthService } f ...

Angular's Async Pipe displaying outdated data

I am encountering an issue with my Angular async pipe setup. Here is the code snippet: <ng-container *ngIf="showProjects && (projects | async) as projectList; else loading"> In my projects.page.ts file, I have the following funct ...

Make the text in the SCSS file placeholder bold

Within my Angular front end application, there is a form containing a textarea: <mat-form-field class="full-width"> <textarea class="left-aligned" formcontrolname="x1" matInput placeholder="some text"/> </mat-form-field> In the co ...

Performing code execution in MVC 5 View every 1 second

I am currently working on a MVC 5 web application and I have a question regarding performing real-time calculations in the view. Below is an example of my view code: var timeRemaining = Model.account.subscriptionEndDate - DateTime.UtcNow; Is there a way ...

React is producing a collection of <td>'s

My React code is very straightforward and it runs smoothly: function Columns(){ return ( <React.Fragment> <li>Hello</li> <li>World</li> </React.Fragment> ); } function Example(){ ...

Guide to creating an HTML table with bokeh

As a newcomer to Bokeh, I've been searching through the documentation for examples but haven't come across an in-built method for creating tables. I have some data that I need to display in tabular format and was wondering what the most straightf ...

How can I remove the gaps between Bootstrap panels on a website?

The Issue https://i.stack.imgur.com/I5EFR.png My problem is with the spacing between the panels, highlighted in red. I've attempted to remove them by using the following CSS: .panel { margin-top: 0; margin-bottom: 0; padding-top: 0; ...