Navigating Angular: Uncover the Secrets of Unwrapping Json Data

I need some help with parsing Json data in Angular TypeScript. The data is structured as follows:

https://i.sstatic.net/H7s8q.png

When calling a REST API, I want to convert a Java class object into an array of model classes. How can this be achieved?

"gameId": 66,
"kashScore": 0,
"samScore": 1,
"wonBy": "Sam",
"createUserId": 0,
"lastModifiedUserId": 0,
"creationDate": "2020-04-20T14:05:44.263+0000",
"lastModifiedDateTime": "2020-04-20T14:05:44.264+0000",
"sessionId": 1000,
"count": null

Here is my model class structure:

https://i.sstatic.net/AqfVh.png

Additionally, there is information for tracking pagination:

https://i.sstatic.net/QOtZP.png

Although I attempted a solution, it resulted in an error:

https://i.sstatic.net/rQbtG.png

Answer №1

Your answer consists of an array structure. The data representing Fifa[] can be found as the initial item in this array.

It's important to note that the HttpClient will not automatically convert the response for you. If your intention is to return a Fifa[] from your service, then it's necessary to map your response accordingly.

return this.http.get<any[]>(fifaUrl).pipe(
  map((response: any[]) => response[0])
);

UPDATE

If your goal is to retrieve all details from the response, you should consider returning an object that conforms to the GetResponse interface within your service method (and potentially reconsidering the naming convention).

fetchAllGamesRecordPaginate(
  pageNumber: number, pageSize: number
): Observable<GetResponse> { 
  const fifaUrl = ${this.baseUrl}/demo/pageNumber/${pageNumber}/pageSize/${pageSize}; 
  return this.httpClient.get(fifaUrl).pipe( 
    map((response: any[]) => {
      const pagination = response[1];
      return {
        fifa: response[0],
        totalRecord: pagination.totalRecord,
        pageSize: pagination.pageSize,
        pageNumber: pagination.pageNumber,
        totalPages: pagination.totalPages
      };
    })
  ); 
}

In this scenario, I am interpreting the response array into an object adhering to the GetResponse interface.

Answer №2

To have the function solely give back an Observable<Fifa[]>, implement a map operator on your Observable:

return this.httpClient.get<GetResponse>(fifaUrl).pipe(
  map((data) => data.fifa)
);

Answer №3

Make sure to update the return type to Observable<GetResponse> and then map the response to fit the GetResponse structure.

fetchAllGamesRecordPaginate(pageNumber:number,pageSize: number):Observable<GetResponse>{ 
  const fifaUrl = ${this.baseUrl}/demo/pageNumber/${pageNumber}/pageSize/${pageSize}; 
  return this.httpClient.get(fifaUrl)
    .pipe(([fifa,paginationInfo]) => (
      {
       fifa ,
       ...paginationInfo
       }
     )
    ); 
}

The API returns an array with two items – the first being the fifa[] array and the second being an object containing pagination information.

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

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

Encountering the identical error message while attempting to execute my application: "Uncaught TypeError: this.microservicesModule.register is not a function."

Despite my repeated attempts to run the application, I am consistently encountering the following error message: "UnhandledPromiseRejectionWarning: TypeError: this.microservicesModule.register is not a function at NestApplication.registerModules ...

PHP code to find the count of a specific value in an array stored within

Is there a way to count the total number of occurrences of CID in the following Array? CID = 992010000021102 I need the count to be 2 - Using Laravel 6 and PHP 7.4 { "status": true, "message": null, "data": [ ...

Error occurred after attempting to make a GET request

What I aim to achieve: I need to send two parameters from the front-end to the back-end. This is the code snippet: In TypeScript file: activeFromActiveToQuery(req?: any): Observable<ResponseWrapper>{ const options = createRequestOption(req) ...

Formatting Generics for JSON Conversion in Scala Play

As I delve deeper into Scala and explore the playframework, there are certain challenges that have been troubling me. In particular, I've been grappling with the issue of using Generics for collections that need to be stored in our database as JSON. ...

I need to change a website into a string so that I can analyze it with javascript. How can I do this?

Currently, I am in the process of creating a website for my video game servers. The admin tool we use outputs the current server status in a .json format as a large text string to this specific URL: My goal is to retrieve the entire text string from the p ...

Issue with displaying error message and disabling button as Keyup event fails to trigger

Is there a way to assess the user's input in real-time on an on-screen form to ensure that the pageName they enter is not already in the navbarMenuOptions array? If it is, I want to switch the visibility of displayName and displaySaveButton. However, ...

What is the best way to choose a particular radio button from a group of radio buttons using typescript?

Is there a way to automatically select a specific radio button when an item is chosen from a dropdown menu on the webpage using a TypeScript function that is triggered by the dropdown selection? ...

Is there a way to guide the user to a different page while still inside a getJSON function?

After making an external call to a JSON file, I am facing an issue where if the JSON data is null (possibly due to expired user session), the user should be redirected to the logout.php page. However, in my current implementation, instead of redirecting, t ...

Comparing angular2/core and @angular/core: What sets them apart?

Maybe this is a silly question, but I've noticed that there are multiple instances of import {Component} from 'angular2/core' and import {Component} from '@angular/core' However, I can't seem to grasp when to use one ove ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

Unable to fetch data using getJSON method

objecten.js var objectData = [ { image: 'gallery/objecten/bear.jpg', thumb: 'gallery/objecten/bear.jpg', title: 'my first image', description: 'Lorem ipsum caption&apos ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

How can you securely transfer the ARRAY OBJECT from JavaScript to PHP using Ajax?

I am attempting to send a Javascript Array Object via Ajax to PHP and then use that object as a true Array on the PHP side. My current approach has not been successful in terms of utilizing the incoming object as an Array within PHP; I can only parse it as ...

Using the `disableSince` option in `mydatepicker` for validating date of birth

Currently, I am utilizing the mydatepicker plugin for my calendar field, specifically for the Date of Birth field. It is important for me to disable future dates by setting the current date as a reference point. While exploring the documentation, I came ...

Testing the value of an input in Angular using unit tests

Currently, I am delving into the official documentation of Angular2 which focuses on unit testing (https://angular.io/docs/ts/latest/guide/testing.html). My struggle lies in setting a component's input field value so that it reflects in the component ...

Create a single JSON object by searching through two collections in MongoDB

Is it possible for you to assist me in combining data from two collections into one JSON format? Users [ user_id, user_name, city_id ] [ { "name": "Anton", "user_id": 1, "city_id": 1 }, { "name": "Vasiliy", ...

Intellisense missing in VSCode for Angular and typings

Attempting to start a new project using Angular 1.5.5 and looking to incorporate TypeScript into my coding process within Visual Studio Code. I have included the necessary typings for Angular in my project: typings install angular --save --ambient I&ap ...

Using Stringify to modify the value of a particular array in Local Storage

Uncertain of the accuracy of my question, but I am attempting to modify a value within a localstorage array. This is what my localstorage currently contains: [{"id":"item-1","href":"google.com","icon":"google.com"}, {"id":"item-2","href":"youtube.com","i ...

Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments. For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types: this.F ...