A guide on iterating through a JSON object fetched using Http in Angular 2/Typescript

I am attempting to extract specific data from my JSON file using http. The structure of the JSON is as follows:

[{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}]

To loop through this retrieved object, I use the following method:

  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );

The getParams() function processes data like this:

    getParams(url: string) {
    return this._http.get(url)
        .map(res => res.json());
}

I have created an interface for the retrieved data within the same .component.ts file where the service is called:

/*Interface for Stats */
interface stats {
name: string;
percent: number;
}

My intention is to iterate through the retrieved object, store it in a local array and then display the data. How can I achieve this in my component file? I have tried various for loops but none were successful.

This attempt failed as TypeScript did not recognize the json variable:

let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});

I have successfully retrieved the data, as I used console log to view the 3 objects received.

Answer №1

Information about statistics:

export class Statistics {
    name: string;
    percentage: string;
    constructor(n, p) {
        this.name = n;
        this.percentage = p;
    }
}

Make sure not to modify the service if it is functioning properly.

Component :

retrieveStatistics(_url: string) {
    let statisticsList: Statistics[] = [];
    this._postService.fetchParams(_url).subscribe(
        data => {
            for (let result of data.Results) {
                let statistic = new Statistics(result.name, result.percentage);
                statisticsList.push(statistic);
            }
        }, err => { /* Handling errors */}
    );
}

Answer №2

The data you received has been assigned to this.results.

this.results = data.Results

You are now attempting to access json.Results.

Update json.Results with this.results

Answer №3

To add the data to your array, you can simply convert it:

fetchData(input: string) {
  return this._http.get(input)
    .map(response => <info[]> response.json());
}

Then in the following snippet:

  this._dataService.fetchData(_input).subscribe(
  result => {
    this.infoArray = result.Info
  },
  error => console.log(error),
  () => console.log('Process complete')
  );

The content of this.infoArray will be your updated array.

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

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

SQL Server - JSON data type enumeration

Supplied declare @json varchar(max)='{ "name":"John", "age":30, "cars": [ { "make":"Ford", "models":[ "Fiesta", "Focus", "Mustang","Vintage"] ,"price":[1100,200,300,999]}, { "make":"BMW", "models":[ "320", "X3", "X5" ] }, { "make":"Fiat", ...

Display the JSON data in a table by utilizing the ng-repeat directive in Angular

Below is the response that I have: Response : response: {"json": {"response": {"servicetype":"", "functiontype":"", "statuscode":"0", "statusmessage":"Success", "data":[{"graphtype":"piechart", "xlabel":"state", "ylabel":"count", "s1":"contact", "s2":" ...

What is the process for automatically initiating a service when importing a module in Angular?

I am curious about how I can automatically run a service within a module upon importing it, without the need for manual service injection and execution. This functionality is similar to how the RouterModule operates. @NgModule({ imports: [ Browser ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...

Error in Angular integrating with Stripe. No definition found for 'Stripe'. Perhaps you meant 'stripe'?

I'm currently in the process of connecting Stripe to my app with redirection, utilizing Angular and typescript. My component contains the following code snippet: var head = document.getElementsByTagName('head')[0]; var script = document.cre ...

Type guards do not work properly on a union of enum types in TypeScript

Recently delved into the concept of Type Guards Chapter within the realm of Typescript However, I encountered an issue where my basic type guards failed to differentiate a union of enums. Why is this happening? enum A { COMMA = ',', PLUS = & ...

What is the most efficient way to retrieve the value of a nested key within a JSON

I am encountering an issue while attempting to retrieve the value of a specific key within a JSON object. The error message I keep receiving is: TypeError: string indices must be integers. Here is the JSON data: {"id": "example", " ...

Child component received an incorrect input value

Utilizing both the "YearComponent" and "StatPeriod" components has presented some challenges for me. Within my YearComponent, I invoke StatPeriod as follows: <app-save-stat-period [dateBegin]="dateBegin" [dateEnd]="dateEnd" byMonth bestNAverage></ ...

AngularJS/Ionic: Issue with HTTP GET requests not completing within a specified timeframe

Attempting to populate options with specific values instead of undefined, but encountering a delay in retrieving the values after the select box has finished loading. https://i.stack.imgur.com/SpEFP.jpg To illustrate, here is the HTML code snippet: < ...

Trouble with Styling React-Toastify in TypeScript: struggling to adjust z-index in Toast Container

Currently in the process of developing a React application utilizing TypeScript, I have incorporated the React-Toastify library to handle notifications. However, encountering some challenges with the styling of the ToastContainer component. Specifically, ...

Dynamically passing output placeholders through ng-content in an Angular component template

Can a component handle dynamic projection in this way? <my-component [date]="2022-03-22"> <p>This particular date falls on a <strong #dayName></strong>! It is in week number <span #weekNum></span> of year &l ...

Ways to delete a blank key from a MySQL json field

I need to modify a MySQL table with a json field that contains an empty key. I am looking for a way to remove this empty key from the JSON field. Current data: update t1 set info = REPLACE(info, '"": "",', ''); The ...

I am unable to utilize autocomplete with types that are automatically generated by Prisma

Currently, I am working on a project utilizing Next and Prisma. Within my schema.prisma file, there are various models defined, such as the one shown below: model Barbershop { id String @id @default(uuid()) name String address String ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

Investigating SCSS Issues: The Problem with Absolute Imports

I am working on a project with the following structure: - my/project - assets - images - image-name.svg - source - components - MyComponent - MyComponent.module.scss - ... - ... ...

Two lines in ChartJS with distinct fill gradients for each

I am facing an issue with ChartJS version 2.6 in my Ionic 3/Angular 4 app. I have set up a line chart config with 2 datasets, but I am struggling to apply individual fill gradients to each line. What I am aiming for is something like this: https://i.stac ...

Leveraging the power of jQuery's $.when and $.then methods for efficiently managing multiple AJAX requests that do not

My goal is to utilize jQuery to retrieve data from both an XML and JSON feed, and then only log the data when both requests are successful. When I comment out getRoomFeed() within the $.when, it returns the correct responseText object for the XML. However ...

Searching the JSON file by its value using Waterline

I am struggling with locating model instances based on the nested address attribute in one of my models. attributes: { address: { type: 'json' } } I have attempted various queries to find model instances located in the same city: Model ...

(Angular4 / MEAN) Making a Request to Local API Yields an Empty Response Body

I'm attempting to send data to an Items API, like this: "data": { "title": "stack", "notes": "asdsad", "time": "19:02", "meridian": "PM", "type": "Education", "_id": "5a2f02d3bba3640337bc92c9", ...