Looking to grab a single value from a JSON file and utilize it in component code within Angular 2 (8.2.8)?

My JSON file contains information about various pages:

{
  "pagesList":
  [
      {
        "pageUrl": "index",
        "imgUrl": "homepage",
        "imgNumber": 17
      },
      {
        "pageUrl": "second",
        "imgUrl": "secondimage",
        "imgNumber": 10
      }      
  ]
}

In order to retrieve the value 17 (from "imgNumber": 17) as a variable in the component code without displaying it in the template, I need to get data from the JSON file using the img-carousel.service.ts:

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

@Injectable({
  providedIn: 'root'
})
export class ImgCarouselService {

  constructor(private http: HttpClient) { }

  getPagesJson() {
    return this.http.get('/assets/from-server/pages.json');
  }

}

Next, I transform the JSON data into an array of objects in the component testzone.component.ts:

import { Component, OnInit } from '@angular/core';
import { ImgCarouselService } from '../img-carousel.service';
import {Pages} from '../pages';

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

  pageParams: Pages[] = [];

  constructor(private imgCarouselService: ImgCarouselService) {   
  }

  ngOnInit() {   
    this.imgCarouselService.getPagesJson().subscribe(data => this.pageParams = data["pagesList"]);    
  }
  
  //imgnum = this.pageParams[0]["imgNumber"];
}

I also create a class Pages to handle the data:

export class Pages {
    pageUrl: string;
    imgUrl: string;
    imgNumber: number;
}

Finally, I display the data on the screen using the template testzone.component.html:

pageParams = {{pageParams | json}}

pageParams[0].imgUrl = {{pageParams[0]?.imgUrl}}

<ul *ngFor="let item of pageParams">
  <li>imgUrl = {{item?.imgUrl}}</li>
  <li>pageUrl = {{item?.pageUrl}}</li>
  <li>imgNumber = {{item?.imgNumber}}</li>
</ul>

However, when trying to assign the value 17 (from "imgNumber": 17) to a new variable in the component code:

imgnum = this.pageParams[0]["imgNumber"];
, the screen goes blank after refreshing the browser. There are no error messages in the IDE, just a blank screen.

How can I access specific data in the component code without displaying it in the template? Any suggestions would be appreciated. Thanks.

Answer №1

To improve your code, I suggest utilizing the http.get overload of the httpclient method.

Instead of

 return this.http.get('/assets/from-server/pages.json');

try

  return this.http.get<Pages[]>('/assets/from-server/pages.json');

Alternatively

Instead of

this.imgcaruselService.getPagesJson().subscribe(data => this.pageParams=data["pagesList"]);    

try

this.imgcaruselService.getPagesJson().subscribe(data => this.pageParams= JSON.parse(data["pagesList"]));  

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

Is it possible to compile using Angular sources while in Ivy's partial compilation mode?

Error: NG3001 Unsupported private class ObjectsComponent. The class is visible to consumers via MasterLibraryLibModule -> ObjectsComponent, but is not exported from the top-level library entrypoint. 11 export class ObjectsComponent implements OnInit { ...

Unresponsive Textbox Input Issue within Reactive Form

My current setup involves an Angular Reactive Form with various controls: this.taskForm = this.formBuilder.group({ storyNumber: new FormControl('', [Validators.required, Validators.pattern('^[A-Z]{2,}[0-9]*-[0-9]{2,}$')]), ...

Is there a way to prevent Angular component lifecycle hooks like ngOnInit/ngOnDestroy from being triggered when nested within one another?

I am currently developing an application with a page structure that resembles the following: Displaying Objects retrieved from Firestore (similar to Instagram posts) Loading Comments (using the object's id to display comments sub-collection) Load ...

Unexpected behavior noticed with Angular Material 2 Reactive Forms: the mat-error directive does not display when validating for minLength. However, it functions correctly for email and required

Try out this Stackblitz example: https://stackblitz.com/angular/nvpdgegebrol This particular example is a modified version of the official Angular Material sample, where the validation logic has been altered to display the mat error for minLength validati ...

Struggling to render the template inside a .vue file in a Vue.js + TypeScript project?

Is anyone familiar with setting up a Vue TS based project? I have encountered an issue where the template data is not being rendered in the browser's DOM. The project structure can be found in this repository: https://github.com/AndrewBogdanovTSS/typ ...

Utilizing Jinja2 with Json

I currently have a JSON File structured like this: { "Google":{ "Web":"www.web.de", "Apps":{ "Drive": "DriveLink", "Dropbox": "DropboxLink" }, "Google Main":"http://mail.google.com", "G+":"http://plus.google.com" ...

A guide on transforming a string into an array of objects using Node.js

Hey everyone, I have a single string that I need to convert into an array of objects in Node.js. let result = ""[{'path': '/home/media/fileyear.jpg', 'vectors': [0.1234, 0.457, 0.234]}, {'path': '/home/med ...

Quill editor fails to trigger the (change) event when I modify the toolbar settings

I am facing an issue with capturing Quill editor events. The code snippet below shows how I am trying to capture the event, but when I change something using the toolbar, the event is not captured. Can someone please help me understand how to get this ev ...

What is the best way to access JSON stringified objects in PHP?

I recently used the following code snippet to send data to the server, but now I'm stuck on how to retrieve the array that was returned using PHP. Any suggestions would be greatly appreciated. $('.ticket-row').each(function() { tickets.push ...

Unable to retrieve the user information using the UID of the current user in Ionic 3

Attempting to retrieve the username of a user by utilizing the current user's UID. The UID is saved in both Firebase database and authentication. this.userid=firebase.auth().currentUser.uid; this.username=firebase.database().ref('Users/'+ ...

Transforming data from RabbitMQ into a string or JSON format

I am currently facing a challenge with a seemingly simple issue. I am trying to extract a message from RabbitMQ and convert it into a string (or later into a JSON object). However, all I am getting is bytes. The Message object appears as a string in this ...

The C# API call encounters issues when using HttpWebRequest, yet functions properly with Postman

I have encountered an issue with my Postman request. Here are the images I am working with: https://i.sstatic.net/oiKXx.jpg https://i.sstatic.net/VFwFn.jpg The expected result should be a URL like this: https://i.sstatic.net/xE7UO.jpg Now, I am attemptin ...

Unable to transmit an object containing a property that includes an array of other objects

I am attempting to send an object that has the following structure: var postBody = { id: userID, objectID: [0, 1], objects: [ {id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0. ...

Verify the presence of a JSON object within the session storage using JavaScript

I'm currently developing a website where some data is stored within the session. In the initial page, I need to verify if the JSON object already exists in the session. Below is the code snippet that's causing issues: var passedTotal = JSON.par ...

I attempted to access the content of an Array that I had mapped, but unfortunately, I was unable to reach it due to an undefined error (no

My plan is to display a series of questions from my JSON database in order to create a quiz. The function I wrote loads the questions and maps them. However, I encounter an issue where I cannot access the questions array ('question' is not define ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Exploring Inheritance in Java JSON Configuration Files

I am working with an API that retrieves details from a JSON config file. For example: "sections": { "Vehicles": ["Car ", "Bus",], "Air transport": ["Helicopter", "Aeroplanes "] ...

Failure to Execute Angular HttpClient Request

I'm facing an issue with firing the HttpClient request. It seems like there might be a problem with importing or providing, but I can't pinpoint where it is exactly. The API works fine, but the call never goes through. Here are the environment/v ...

The most efficient method for quickly loading specific sections of JSON responses into a pandas DataFrame object

Having a series with numerous JSON responses, all of which are quite sizable. Example Display {0: '{"city":"Campinas","bot-origin":null,"campaign-source":null,"lastState":"productAvailabilityCpfRequest","main-installation-date":"22/09/2021","userid": ...

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...