Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation

{
 "data": [
          {"id":"1","commid":"0","subject":"test1subject","body":"test1 body"},  
          {"id":"2","commid":"1","subject":"lkjhlkjh","body":"nbvjhg"}
 ]
}

Instead of returning an array of data with objects, it should return as Message[]. How can I adjust this to function like the example? It must return a Message[]

return this.http.get('messages.json')
                .toPromise()
                .then(this.extractData)
                .catch(this.handleError);

private extractData(res: Response) {
   let body = res.json();
   console.log(body);
   return body.data || { };
}

Here is how the code looks in my component

export class Message {
   id: number;
   commid: number; // community ID that this message belongs to
   subject: string;
   body: string;
}
   msgs:  Message[];
   this.msgService.getMessages().then(messages => {
       this.msgs = messages;
   });

For illustration purposes, here is a link to the Angular doc sample: http://plnkr.co/edit/KZGeyULqrcuZDSeg0CkF?p=preview

Answer №1

This is the PHP code I used to achieve my desired outcome:

$item_type = "products";
$rows = array('products' => array());
while($row = mysqli_fetch_assoc($result)) {
$rows['products'][] = $row;
}

echo json_encode($rows,JSON_NUMERIC_CHECK);

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

Using Angular's typeahead with RxJs switchMap for subscribing to data sources

Implementing the Angular bootstrap Typeahead plugin for displaying colors. However, I am facing difficulty in resolving circular references like I have done in other parts of my project. The RxJs SwitchMap operator is not working for me in this case. Are t ...

Sending information to a service from the main.ts file in an Angular application

Within my Angular CLI application, I have a main.ts file that includes the following export statement. This file serves as a microservice that receives CONTEXT from another microservice. export default { async mount({ rootElement, context }: Extension) ...

Using NestJS to import and inject a TypeORM repository for database operations

This is really puzzling me! I'm working on a nestjs project that uses typeorm, and the structure looks like this: + src + dal + entities login.entity.ts password.entity.ts + repositories ...

Issue with Angular and SCSS: Rgba function does not properly interpret HEX value

Attempting to retrieve the background color of the Angular theme, I encounter an issue where it is represented in HEX format and needs transparency added. This is how the variable is defined: :root { --opacity: .15; --primary: #4caf50; --accen ...

Incorporating JSON data into an array using d3

I'm currently working on mapping JSON data to an array variable in d3. Below is the JSON I am using: [ { "Impressions": "273909", "Clicks": "648", "CPM": 4.6388278388278, "Cost": 1266.4, "CPC": 1.9543209876543, "Campaign": "C ...

Automatic type inference for TypeScript getters

It appears that Typescript infers field types based solely on the private variable of a field, rather than taking into account the getter's return type union (1) or inferring from the getter itself (2): test('field type inference', () =& ...

Transforming JSON information into a data frame

Is there a way to convert JSON data like this into a data.frame? library("rjson") fromJSON("[{'id': 18, 'name': 'Drama'}, {'id': 28, 'name': 'Action'}, {'id': 10749, 'name': & ...

`How can I stop typescript from converting dynamic imports to require()?`

Currently, I am in the process of creating a Discord bot using discord.js. Interestingly, discord.js does not seem to be compatible with ESM modules, which has been causing some complications in my project. As a result, I have resorted to utilizing CommonJ ...

Dealing with Dependency Injection Problem in Angular 6

I am grappling with a challenge in my cross-platform Angular application. The crux of the issue is determining the platform on which the app is running and accordingly injecting services. Below is how I've structured it: @NgModule({ providers: [ ...

Encountering an issue while attempting to incorporate an interface within a class in TypeScript

Can someone please help me figure out what I'm doing wrong? I'm attempting to implement an interface inside a class and initialize it, but I keep encountering this error: Uncaught TypeError: Cannot set property 'name' of undefined at n ...

What is the process for adding an element using Angular Material2 design?

I am in the process of creating a template where, upon clicking a button, I want to append specific elements. While I have successfully appended the elements using the code below, I am facing challenges with adding styles and integrating angular-material2 ...

Tips for configuring jQtree to initially display the tree structure from the HTML source

Up to this point, I have utilized jQuery TreeView for the navigation menus on my website. However, as the main navigation menu has grown significantly in size (40869 bytes out of 67054 bytes), I am seeking a way to streamline it by using AJAX calls to fetc ...

Having difficulty displaying JSON retrieved from requests

I'm currently facing an issue with pulling JSON data from a website. It seems that the information is not being printed as expected. I am unsure whether the problem lies within my code or if there is an issue with the site itself. Below is the snippet ...

Eliminate the loading screen in Ionic 2

Within my app, there is a button that triggers the opening of WhatsApp and sends a sound. Attached to this button is a method that creates an Ionic loading component when clicked. The issue I am facing lies with the "loading.dismiss()" function. I want the ...

Is there a way for me to dynamically incorporate new elements into this object?

I am working with an object msg.data that contains the following information: { "user_id": 1, "success": "true" } Now, I want to add a name field to this list: { "user_id": 1, "success": "true", "name" : "giri" } I have attempted the following ...

Retrieve the value from an input tag that is only displayed based on a condition using *ngIf

In my HTML form, I have implemented conditional visibility of input fields based on the radio button selection using *ngIf. <table> <tr> <td><label>name</label></td> <td><input #name />&l ...

Eliminate Elements from Array - Angular Four

I am currently developing a basic to-do app using Angular4. The setup of the app is structured as follows: Form Component: Responsible for adding items to the to-do list Item Component: Represents individual to-do items App Component: Contains a *ngFo ...

Creating JSON data based on user provided input within a text area

I am currently developing an application that requires a json datafile to generate certain elements. I am looking to gather user input through this form: { "nodes": [ { "id": "n0", "label": "A node", "x": 0, "y": 0, "si ...

Angular setup prompting for anonymous usage statistics collection by the Angular development team

This is my first time installing Angular and I ran into confusion at this step. The terminal message prompted me with the option to share anonymous usage data with the Angular Team at Google under their Privacy Policy. Here's what it said: ? Would y ...

In TypeScript, what is the format in which the final type result of a generic utility type is shown?

After utilizing the provided code, I have encountered an issue with retrieving the ultimate type of type A in the editor. Despite my efforts, the editor persistently showcases the composite form of the generic utility, complicating the process of verifyi ...