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

Every time I attempt to submit the login form on the Ionic and Angular page, instead of capturing the values of the form group, the page simply refreshes

Struggling with submitting the login form in Ionic and Angular? When attempting to submit, the page reloads instead of capturing the form group values. I am utilizing angular reactive forms and form builder within the ionic framework. Need assistance in id ...

Modify the default JSON structure generated by the Java controller

My current situation involves a controller that sends back a list of objects using a ResponseEntity. The returned JSON follows this format: [ { “name”:”a”, “classes”: [ “1”,”2”,”3” ] }] I am looking to ...

Check the @versionColumn value for validation prior to the entity save operation in TypeORM

I am currently in the process of saving data in a PostgreSQL database using TypeORM with NestJS integration. The data I am saving includes a version property, which is managed using TypeORM's @VersionColumn feature. This feature increments a number ea ...

Executing multiple instances of the cascading dropdown fill method in Angular 7

I am currently working on an Angular app that includes cascading comboboxes for country and state selection. However, I have noticed that the get states() method in my state.component.ts file is taking a long time to run. What could be causing this issue? ...

Utilize JSON Parsing in Inno Setup Using a JSON Parser

For my Inno setup project, I encountered an issue when trying to parse JSON using a dll function. After days of troubleshooting an access violation error, I decided to explore parsing JSON directly within the Inno Setup. I am interested in utilizing the Js ...

The pagination button in angular bootstrap UI caused the button to shift when clicked

I am currently using angular bootstrap's UI pagination to display results with next and previous buttons. The result sets are displaying correctly, however, I am encountering an issue when clicking on the pagination buttons. Specifically, the buttons ...

Using Jquery to send json data to a webserver via Ajax (API)

Currently, I am attempting to use AJAX to post data to a JSON file (API) on a server. As part of this process, I have implemented dragging functionality for two Kineticjs shapes on the stage. Upon stopping the drag action, my goal is to save the updated x ...

Connecting Select2 with MySQL database using PHP: A step-by-step guide

I've been struggling to connect my select2 input to fetch results from a MySQL database using mysqli connection. Despite trying various solutions, I haven't been able to make it work and keep getting a message saying "no results found." The most ...

Unsure about module loading with system.js and navigating Typescript

I am currently in the process of transitioning an ASP.Net MVC application to Angular2, and I've encountered some perplexing behavior that I can't seem to grasp. Within my Angular2 app, I have a separate Layoutview that allows me to switch betwee ...

mongodb is experiencing issues with the findOneAndUpdate operation

Below is the code snippet for updating the database. let profileUrl = 'example' UserSchemaModel.findOneAndUpdate({_id:userId}, {$set: {profileUrl:profileUrl} }, {new:true}) .then((updatedUser:UserModel) => { console.log(updatedUser.profil ...

What is the reason behind VS Code not showing an error when executing the command line tsc shows an error message?

Deliberately introducing a typo in my code results in an error. Here is the corrected code: declare const State: TwineState; If I remove the last character and then run tsc on the command line, it throws this error: tsc/prod.spec.ts:7:22 - error TS2304: ...

submitting a JObject as a payload to a request

I just came across an interesting article by Rick Strahl on passing multiple POST parameters to Web API Controller methods. You can check it out here. In the article, he talks about using JObject in the action and provides an example of a controller imple ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

run a function once ngFor has completed rendering the data

I'm attempting to run a function every time my ngFor finishes loading data from the API. However, the callback only works on the initial load of the ngFor. How can I make sure that the callback is executed whenever my ngFor data changes? I found a ...

Tips for converting text input in a textbox to a Date value

My knowledge of Angular is limited, and we are currently using Angular 10. In our application, there is a textbox where users need to input a date in the format 10202020. This value should then be reformatted as 10/20/2020 and displayed back in the same ...

Calculating Events with the onChange Method in Typescript

How do I calculate the total ticket price when I adjust the number of individuals? HTML Code : <div class="row"> <div class="col-md-6"> <label for="person">Person</label> <div class="form-group"> ...

Utilizing Angular 8's Reactive Form to Transform Checkbox Event Output into a String Format

My form is reactive and includes a field called Status, which can have the values 'A' or 'I': this.form = this.formBuilder.group({ result_info: this.formBuilder.array([ this.getResultcontrols()]), stat ...

Angular Material Rotate Ink Bar to Vertical Orientation

After wanting to change the orientation of Angular Material's Tab Component to vertical, I visited this page (Tabs) and experimented with the CSS. By making the necessary adjustments, I successfully displayed the tabs vertically using the following CS ...

A guide on extracting information from a personal Flask JSON route endpoint with Axios

I am looking to store JSON data in a variable using Axios in Javascript. The JSON endpoint is generated by my own server's route http://123.4.5.6:7890/json. I have been successful with this function: async function getClasses() { const res = await ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...