Unable to convert JSON response into an array while using Angular 2

I'm currently working on converting a JSON response into an array within Angular 2. Below is the code I have implemented:

.ts file

response;
resp;
constructor(private http:Http) {
}
get()
{
this.http.get("http://localhost:3000/items")
.map(res=>res.json())
.subscribe(data=>this.response = JSON.stringify(data))

this.resp = JSON.parse(this.response);
}

component.html

{{response}}
<ul>
<li *ngFor="let k of resp">{{k}}</li>
</ul>

</div>

Even though {{response}} displays the entire JSON content, I'm struggling to iterate through the response retrieved in resp even after using JSON.parse().

Any suggestions on how to successfully convert the response into an array and access the individual properties?

Answer №1

From the code provided, it appears that you are not assigning a value to the 'resp' variable.

You seem to be storing a value in the 'response' variable and then iterating over the 'resp' variable.

To rectify this, consider using (let k of response) instead of (let k of resp).

Answer №2

To iterate over arrays in Angular, you can use ngFor. However, if your response is a JSON object, you cannot directly iterate through it using ngFor. In this case, you will need to create a custom pipe to iterate over the JSON object.

You can define a pipe like so:

@Pipe({ name: 'keys',  pure: false })
export class KeysPipe implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)
    }
}

After creating the pipe, import it into your module and add it to the declarations. Then, you can use it in your HTML like this:


{{response}}
 <ul>
    <li *ngFor="let key of resp | keys">{{key}}</li>
  </ul>

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

Encountered an error while running Spark's Structured Streaming: pyspark.sql.utils.StreamingQueryException - assertion failed due to an invalid batch

In my Spark Structured-Streaming application, I am reading JSON data from s3, performing transformations, and writing it back to s3. Sometimes, the job encounters errors and re-attempts without any visible loss or corruption of data. However, the error mes ...

Using JSON as a variable solely for determining its type and guaranteeing that the import is eliminated during compilation

In my TypeScript backend project with Node as the target runtime, I have a JSON file that is auto-generated within my repository. I use the following code to import the JSON file in order to get the type of the JSON object: import countries from '../g ...

A method for handling specific subsets of an enum in a secure and controlled manner

I have an enumerated type called Country and another type that represents a subset of European countries. I want to handle values within this subset differently from others. Currently, I am using an if statement with multiple conditions, but it could get u ...

Attempting to change the id property into a Mongoose ObjectId

Here is a snippet of my code: acceptContactRequest: async ( _: any, { userId }: IUserInfo, context: ExpressContext ) => {.....} The interface IUserInfo looks like this: export interface IUserInfo { username: string; password: ...

Can anyone provide guidance on incorporating lodash into an Ionic 2 project?

Recently, I began diving into a new project that involves Ionic 2. TypeScript is still fairly new to me, and I've been brainstorming ways to integrate lodash into my project. Have any of you tackled this before and can offer guidance on how to achiev ...

Establishing a connection to a MySQL database in passport.js to deserialize user

Is there a way to handle deserialization of a User in passport.js when connected to a database? It was functioning properly with an array, but encountered issues once linked to the database. What steps can be taken to resolve this problem? Error: Failed ...

Error: React-router and typescript not playing well together!

During the development of my React app using TypeScript, I encountered a minor issue that I haven't been able to resolve yet. This is a snippet of my code: App.tsx import * as React from 'react'; import * as ReactDOM from 'react-dom ...

JSON-formatted public data sets

Can anyone point me towards a public dataset in Json format? Ideally, I am searching for one that falls within the 10-20GB range. The larger datasets I've come across so far have all been in XML format. ...

Strategies for increasing the number of images in Angular

At the start, 15 images are displayed from the API. However, the "Get dogs" button should load an additional 15 images each time it's clicked, but currently, it doesn't work. How can we fix this issue? http.service.ts - a service that interacts ...

Transferring JSON information to the primary activity

My current project involves connecting my app to a MySQL database using JSON and PHP. The PHP script I have created returns a JSON array that determines the status of the light (either true or false). To make things more organized, I decided to put the JS ...

Unable to execute rspec in Ruby on Rails

I am new to RoR and encountering an error message when running rspec in Rails. The error message reads: You have already activated json 2.0.2, but your Gemfile requires json 1.8.6. Prepending bundle exec to your command may solve this. (Gem::LoadError) I ...

How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

Testing RestFul API endpoints using PHPUnit with terminating response

Currently, I am facing an issue while trying to PHPUnit test an action within my ZF2 project. The APIs are configured to return a JSON string using the die($jsonObject) function. This is causing the PHPUnit test to abruptly halt its processing and displa ...

Troubleshooting: Resolving the Error "Cannot find Property htmlFor on Custom React Component"

I am currently working with a custom component that looks like this: import React from "react"; import classnames from 'classnames'; import { ButtonVariantColor } from '../types/button'; export type IconButtonProps = { e ...

"Double the Data: A D3.js JSON Tale of Two Creators

I found inspiration from this example: http://bl.ocks.org/mbostock/1062288 to create a collapsible Force Layout. One challenge I'm facing is how to display a graph where a single node is connected to two parent nodes. father father | | ...

Error when accessing JSON property in Angular with Ionic 2: A Strange TypeError

I have implemented a provider in my Ionic project to fetch the user object from storage. Below is the code: import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class ApiProvider { ...

Sorting arrays in Typescript

Is there a way to alphabetically sort an array of objects in Typescript based on a specific field? The array I have currently looks like this - https://i.stack.imgur.com/fQ3PA.png I'm interested in sorting it alphabetically by the 'channel' ...

Transform string value into the required integer type argument

After receiving a dictionary of data from another viewController, I encountered a conversion error when attempting to retrieve the id value from the dictionary! var commentsData = [JSON]() @IBAction func AddCommentButton(_ sender: Any) { let co ...

Generate arrays with custom names by parsing JSON data

Currently, I am retrieving data from a MySQL database and converting it to JSON before passing it to a JavaScript class for chart display purposes. The challenge lies in creating arrays required by the chart from the JSON object without manually creating a ...