Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs.

Although the code works flawlessly when I manually set id1 and id2 as 1 and 2 in the

this.blog=data[this.id1].blogs[this.id2];
line,

I encounter an error stating

TypeError:_data_json__WEBPACK_IMPORTED_MODULE_2___namespace[this.id1] is undefined
without any modifications.

import { Component, OnInit } from '@angular/core';
import * as data from '../data.json';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
  id1;
  id2;
  sub;
  blog;
  
  constructor(
    private _Activatedroute: ActivatedRoute, 
    private _router: Router
  ) {}
  
  ngOnInit() {
    this.sub = this._Activatedroute.paramMap.subscribe(params => {
      console.log(params);
      this.id1 = Number(params.get('id1'));
      this.id2 = Number(params.get('id2'));
      this.blog = data[this.id1].blogs[this.id2];
    });
  }
}

Even when substituting id1 and id2 with other variables, the same error persists.

edit: I made a change from

import * as data from '../data.json';
to
const data=require('../data.json');
, and it provided the correct outcome. However, the reason behind this behavior eludes me, so I welcome further discussion on this topic.

Answer №1

params.get function only retrieves string values. It is recommended to convert the string into a number before sending it to the data processing function.

Answer №2

Consider implementing the following code snippet

this.website = data[+this.id1].websites[+this.id2];

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

After executing a query to a PostgreSQL database, I encountered an error preventing me from using res.send(). The error message stated: "Cannot set headers after they are sent to the client."

It may sound strange, but it's a true story. I was busy building an API on node.js when I encountered a peculiar error. As soon as the first res.status().send() was triggered during query processing, VS Code threw a "Cannot set headers after they are ...

Retrieving values from nested arrays in Vue.js

I'm currently delving into Vue3. My goal is to extract the values from an array within an array in order to create a neat table. Once extracted, I plan to separate these values with commas. For more information, you can visit this link: https://stack ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Is it possible to open a PDF in Acrobat directly from a single button click on a user interface created with Angular/JS?

Currently, I am in the process of developing an Angular/java webpage that will allow users to interact with various forms. At the moment, if a user wants to edit a PDF, they must download it and then go to their downloads folder to open it in Adobe Acrobat ...

Looping through a single object with an Ajax call

When I make this ajax call, it only displays the last object from the JSON file instead of all objects. Can someone help me understand why? Ajax Call var ajax = new XMLHttpRequest(); var data = 'data.json'; var url = 'http://localhost: ...

Executing an asynchronous function within an Angular 7 interceptor is crucial

I've been working on creating an interceptor to handle a situation where a function needs to be called to refresh the session upon receiving a 401 error response. Here's what I have so far but I'm facing build issues and struggling to figure ...

Is there a way to extract a list of 40 unique objects by fetching solely the userName values from a JSONArray?

I am working with a JSONArray that contains various userNames and I need to extract these values and map them to key value pairs in the format {"username": "name"}. There are a total of 40 names in the list. However, when I retrieve the data, I am getting ...

What steps are involved in establishing client-side AJAX polling?

I need some assistance with my app's functionality regarding Delayed::Jobs. Time to reach out for expert advice! My application generates Delayed::Jobs and I want to show users a visual indication of the job status as they progress. Let's assume ...

Retrieve data from an array of JSON objects within a JSON object using ReactJS

Trying to extract data from JSON like this: { "id": 371, "city": "London", "name": "London Station", "trains": [ { "id": 375, "number": "1023", "numberOfCarriages": "21" } ] } Interes ...

"After completing the task, the textview does not get updated in onpost

I am currently working on creating a movie catalogue app and facing an issue with the DetailActivity. The problem arises when I click on the first movie to view its details, then press the back button. Upon clicking on another movie, the app still displays ...

Importing data from an external file into an array using AngularJS

Hey there, I'm new here on Stack and hoping someone can lend a hand because I've hit a roadblock! I'm working with an AngularJS script that generates multiple icons using data from a simple array. Each icon is linked to a YouTube video. Th ...

Iterate through each child <div> element with the ID of "status"

Currently, I am utilizing a $.each function to iterate through my JSON data and parsing it. Following that, I intend to compare the data extracted from the JSON output with the .text() content of each div that has an ID of "status". The issue arises at th ...

The implementation of a universal translation system in Express JS

I have developed a straightforward translation module for Express JS. It exists as a global object in the application scope and is initialized during application runtime: translator.configure({ translations: 'translations.json' }); I have i ...

"An error in the signature index results in the failure of the

I'm encountering a coding issue that's puzzling me. The TypeScript index signature I included in my code is as follows: const ships: { [index: string]: Ship } = {}; This snippet of code contains the problematic line: recieveAttack(e: any) { ...

error in jquery when splitting

I encountered an issue while trying to split data for checkboxes. var ukuran = data['model'].ukuran_model; var cek = ukuran.split(",").join('], [value='), $inputs = $('input[name^=ukuran]'); $inputs.filter('[value=&a ...

Extracting Node.js data within a Node.js script

Can a node.js file be parsed to execute part of the code within another node.js file? I am attempting to parse a node.js file from within a different script. I do not have control over the contents of the file, but it always contains a function called get ...

Exploring Gson's method for deserializing JSON containing optional fields

I'm currently utilizing Gson for deserializing a JSON string obtained from an API using the code snippet below. Gson gson = new Gson(); Map<String, CustomDto> test = gson.fromJson(result, new TypeToken<Map<String, CustomDto>>() {}.g ...

Utilizing jQueryUI for rendering tabbed content with JSON data

Although I have the ability to load JSON data that is returned (appearing "as is" in my HTML page), I am facing an issue where the raw JSON data does not disappear. The code I have used is as follows: $( "#tavole" ).tabs({ cache : false, event: "m ...

What is the best way to utilize the to_json method within a loop to generate a JSON file for each key, value pair? The key should represent the filename for the JSON file, while the value should

Currently, I have a dictionary where the keys are strings and the values are dataframes. My objective is to create a JSON file for each dataframe in the dictionary, where the file name corresponds to the key string of the dataframe. I attempted to achieve ...

Using the VSCode debugger to place a breakpoint within a Typescript package that has been symlinked using `npm link`

I'm currently troubleshooting a NodeJS application and its associated typescript packages, which have been linked using `npm link`. The directory structure is as follows: /root/package-a # typescript package /root/package-b # another typescript packa ...