Exploring techniques for looping through JSON response data in Angular 2 using TypeScript

When I receive this JSON data as a response, I attempt to iterate through it inside the "component template attribute" in order to display the content within an "li" tag HTML.

{
  "items": [
    {
      "aliases": [
        "http://www.xyz.co",
        "http://facebook.xyz.co"
      ],
      "styling": {
        "tag_background_color": "#E0EAF1",
        "tag_foreground_color": "#3E6D8E",
        "link_color": "#0077CC"
      },
      "related_sites": [
        {
          "relation": "meta",
          "api_site_parameter": "meta.xyz",
          "site_url": "http://meta.xyz.co",
          "name": "Meta Stack Overflow"
        },
        {
          "relation": "chat",
          "site_url": "http://chat.xyz.co",
          "name": "Stack Overflow Chat"
        }
      ],
      "markdown_extensions": [
        "Prettify"
      ],
      "launch_date": 1221436800,
      "closed_beta_date": 1217462400,
      "site_state": "normal",
      "high_resolution_icon_url": "https://cdn.sstatic.net/Sites/sxyz/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f3e2e2fef7bfe6fde7f1fabffbf1fdfcd2a0bce2fcf5">[email protected]</a>",
      "favicon_url": "https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico",
      "icon_url": "https://cdn.sstatic.net/Sites/xyz/img/apple-touch-icon.png",
      "audience": "professional and enthusiast programmers",
      "site_url": "http://xyz.co",
      "api_site_parameter": "xyz",
      "logo_url": "https://cdn.sstatic.net/Sites/stackoverflow/img/logo.png",
      "name": "Stack Overflow",
      "site_type": "main_site"
    },
    {
      "aliases": [
        "http://www.xyz.co",
        "http://facebook.xyzw.co"
      ],
      "styling": {
        "tag_background_color": "#E0EAF1",
        "tag_foreground_color": "#3E6D8E",
        "link_color": "#0077CC"
      },
      "related_sites": [
        {
          "relation": "meta",
          "api_site_parameter": "meta.xyz",
          "site_url": "http://meta.xyz.co",
          "name": "Meta Stack Overflow"
        },
        {
          "relation": "chat",
          "site_url": "http://chat.xyz",
          "name": "Stack Overflow Chat"
        }
      ],
      "markdown_extensions": [
        "Prettify"
      ],
      "launch_date": 1221436800,
      "closed_beta_date": 1217462400,
      "site_state": "normal",
      "high_resolution_icon_url": "https://cdn.sstatic.net/Sites/xyz/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f8998888949dd58c978d9b90d5919b9796b8cad688969f">[email protected]</a>",
      "favicon_url": "https://cdn.sstatic.net/Sites/sxyz/img/favicon.ico",
      "icon_url": "https://cdn.sstatic.net/Sites/xyz/img/apple-touch-icon.png",
      "audience": "professional and enthusiast programmers",
      "site_url": "http://stackoverflow.co",
      "api_site_parameter": "stackoverflow",
      "logo_url": "https://cdn.sstatic.net/Sites/xyzw/img/logo.png",
      "name": "Stack Overflow",
      "site_type": "main_site"
    }
  ]
}

The JS code snippet is provided below:

@Component({
    selector: 'http-test',
    template: ` 
       <ul>    
          <li *ngFor="#data of httpData>{{data.items.related_sites[0].name}}  //attempting to iterate through the response data.
          </li>
       </ul>
     `,
     providers:[HTTPTestService]

})


export class HTTPTestComponent {
    public httpData;

    constructor (private _httpService: HTTPTestService){}

    getStack(){
      this._httpService.getItemData()
          .subscribe(             
             data =>this.httpData = JSON.stringify(data),
             error => alert(error),
             () =>console.log("finished")
          );
    }
    ngOnInit() {
      this.getStack();
    }
 }

I've made attempts but have been unable to achieve my desired outcome. Any assistance would be greatly appreciated. Thank you.

Answer №1

Give this a shot

  <li *ngFor="let item of serverResponse.items>{{item.related_sites[0].name}}  //testing the iteration of server response data.
  </li>

Answer №2

Check out the code snippet below:

<ul class="menu">
  <li *ngFor="let item of httpData.items>
    <ul>
      <li *ngFor="let alias of item.aliases>
        {{alias}}</br>
      </li>
    </ul> 
    ..
    <ul>
      <li *ngFor="let related_site of item.related_sites>
        {{relation}}
        {{api_site_parameter}}
        {{site_url}}
        {{name}}
      </li>
    </ul>
     ..
     ..
  </li>
</ul>

Answer №3

One issue that stands out is within the getStack() function, specifically where you subscribe to the http response observer. There seems to be a conversion error as you are converting the response to a string using JSON.stringify(data). It's important to have an object instead of just its JSON string form so that you can easily access its properties in your template.

The code snippet for the HTTPTestService class was not provided, which leaves uncertainty about whether any post-processing, such as a .map(...) call, is done on the response before passing it to the subscriber(s). If you are returning the original Observable<Response> to the subscriber, then you will need to parse the response body into a valid object. You can achieve this by replacing the following line:

data =>this.httpData = JSON.stringify(data)

with

data => this.httpData = data.json()

It's advisable to handle this conversion in your service file, ensuring that it already returns a valid object to your component. Additionally, remember to place the parsing call within a try-catch block to handle scenarios where the server sends back an invalid JSON response.

After resolving the issue with parsing the http response, you should be able to loop through your data according to the guidance provided by Amol Bhor in another related answer.

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

Tips for transferring arguments between package.json scripts

Looking to reduce script duplication in my package.json. Parameterizing scripts would be very helpful. How can I access an argument from any position within a script (keeping it within package.json) without node appending the argument to the end of the li ...

Error in Angular 6: There is no property '$' on the type 'Window'

I've been facing an issue while trying to integrate jQuery and jsGrid into my Angular 6 project. The project won't compile unless I comment out a specific part of the code. Once I do that, the compilation works, but I still encounter an error. I& ...

TS2339: The specified property is not present on the Angular type

Hey everyone, I've recently embarked on my Angular learning journey. Unfortunately, I'm currently facing this Error: 32 this.warning.error.push(entry.name+': '+entry.error); ~~~~~ src/app/dashboard/dashboard.component ...

Matching the types of method parameters to the types of callback function parameters in Typescript generics

I am currently working on creating a class that takes a function as a parameter in the constructor. The function can have arguments of any type. My goal is to add a method to the class that also accepts the same arguments as the function parameter, essenti ...

The positioning of Material UI InputAdornment icons is located beyond the boundaries of the TextField input area

I am struggling to understand why my InputAdornment is not positioned correctly. There doesn't seem to be any style in my code that would affect the location of the icon within the TextField (such as padding or flex properties). Currently, the calen ...

Using a reactive form in Angular 12, the selected form group is initialized with an empty array

.html File <div *ngFor="let analysis of analysisFormArray.controls; let i = index" [class.selected]="analysis === selectedAnalysis"> <div [formGroup]="analysis" (click)="onSelect(analysis)"> ...

Struggling to retrieve image source from an anchor using [routerLink] in Angular and Jest Testing?

Currently, I am in the process of testing a component that contains an <img> tag nested within an element with an *ngIf directive. Despite ensuring that the if condition is always met, retrieving the image source string proves to be challenging. Angu ...

Rendertron and the importance of <script> tags

Recently, I implemented Rendertron for my Angular 6 application and realized that it wasn't rendering the <script> tags. Does anyone have insight on how to configure Rendertron to render these tags properly? The main reason I am looking to addr ...

Is there a way for me to receive a unique selection of items from an array for every accordion item?

I am currently facing an issue where all three accordion items have the same set of objects, but I want each of them to have a different set. Here's what I have attempted so far, but it is not working as expected: const meetingRooms = [ { ...

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

Tips for Programmatically Choosing a Single Value Option in Angular

I have implemented a "Select All" feature in my select list to clear all other selected options and only choose the "All" option. However, I am facing an issue where I can clear out all selected options but cannot select the "All" option. <mat-form-fiel ...

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

Unlocking the full potential of Bootstrap with the colspan feature

I'm currently in the process of developing an Angular 2 and Bootstrap application. Here's a snippet of my code: <div class="panel-body"> <table class="table table-striped table-bordered" style="width:100%;"> < ...

Utilizing numerical values in useParams - A beginner's guide

Trying to access specific data from my json file using an ID, like "http://localhost:3001/pokemons/3", leads to a 404 error. All the data is visible at http://localhost:3001/pokemons. It seems that useParams doesn't want me to use id as a number - q ...

Error: Unable to locate loading.gif file within the Angular library

In my current setup, I have a monorepo that includes a standard Angular application and an Angular workspace with a library at the same level as the app. After configuring the main app to recognize the library, I am able to use the components without any ...

Error: The reference 'GetServerSideProps' is being incorrectly used as a type instead of a value. Perhaps you intended to use 'typeof GetServerSideProps' instead?

Index.tsx import Image from 'next/image' import Head from "next/head" import { sanityClient, urlFor } from "../sanity" import Link from 'next/link' import {Collection, address} from '../typings'; import ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

Validate if the program is currently running as "ionic serve" before implementing a conditional statement

Is there a method to determine if the ionic serve CLI is currently active (indicating it's not running on a physical device) within the code and use it as a condition? My problem: I have a Cordova plugin that returns a response to Cordova. When usin ...

Challenge faced: Angular array variable not refreshing

I am currently working on a map application where users can input coordinates (latitude and longitude). I want to add a marker to the map when the "Add Waypoint" button is clicked, but nothing happens. Strangely, entering the values manually into the .ts f ...