Converting Http Client GET response into an array of objects with specified type

I have a model set up for the data I am retrieving through a GET request, and my goal is to map this data to an array of Player objects.

This is an example of the response data received from the API:

[
    {
        Id: 1
        PlayerName: "Dave",
        FirstSeason: 2013,
        LastSeason: 2016,
        BattingAverageRecord: [340, 210, 220, 300]
    },
    {
        Id: 2
        PlayerName: "Dennis",
        FirstSeason: 2013,
        LastSeason: 2016,
        BattingAverageRecord: [230, 221, 312, 240]
    },
    {
        Id: 3
        PlayerName: "Mary",
        FirstSeason: 2010,
        LastSeason: 2013,
        BattingAverageRecord: [330, 123, 151, 307]
    }

];

A model has been established for this data:

export class Player {
    constructor(public Id: number,
                public PlayerName: string, 
                public FirstSeason: number, 
                public LastSeason: number, 
                public BattingAverageRecord: number[]) 
    {
        this.Id = Id;
        this.PlayerName = PlayerName;
        this.FirstSeason = FirstSeason;
        this.LastSeason = LastSeason;
        this.BattingAverageRecord = BattingAverageRecord;
    } 
}

Now, my objective is to link the response data to an array of Players:

retrievePlayer(): Observable<any> {

    return this.http.get<Player[]>(this.playerAPI)
        .pipe(
            map(data => {
                return new Player(data.Id, data.PlayerName, data.FirstSeason, data.LastSeason, data.GPARecord))
            }
        )
}

I tried using

new Array(new Player(data.id ...))
, but I know that's incorrect too.

Answer №1

When mapping data, you have the ability to organize it into a new structure as shown below:

fetchPlayerDetails(): Observable<<Player[]> {

    return this.http.get(this.playerAPI)
        .pipe(
            map(response => {
               return {
                 Id: response.Id,
                 PlayerName: response.PlayerName,
                 FirstSeason: response.FirstSeason,
                 LastSeason: response.LastSeason,
                 BattingAverageRecord: response.GPARecord

               }
            }
        )
    }

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

Angular 7: Unable to connect with 'messages' because it is not recognized as a valid attribute of 'message-list'

Currently, I am embarking on an Angular journey to develop a hobby chat project using Angular 7 for educational purposes. My main hurdle lies in comprehending modules and components, which has led me to encounter a certain issue. The Challenge In the tut ...

It is not possible to install Angular CLI on a Mac computer

My Mac computer is currently running macOS Ventura 13.1 I managed to install node (v18.12.1) & npm (8.19.2) successfully on the system. However, when I attempted to run npm install -g @angular/cli to install Angular CLI, it resulted in the following e ...

Tips for providing a base URL in Angular to fetch images from an API

How do I access the API URL to retrieve images from a database? <table class="table"> <tr> <th>Id</th> <th>Image</th> </tr> ...

The correct method for handling arrays with overlapping types and narrowing them down again

When working with arrays containing different types in TypeScript, I often encounter issues with properties that are not present on all types. The same challenge arises when dealing with various sections on a page, different user roles with varying proper ...

Leveraging Angular's capability to import files directly from the assets

I recently installed a library via npm and made some modifications to one of the modules. python.js If I delete the node_modules folder and run npm install, I am concerned that I will lose my changes. Is there a way to preserve these modifications by mov ...

Experience the advanced NgPrime p-dropdown template with templating, filtering, and a clear icon that collapses when wrapped within a form element

Check out this link for a demo Whenever I enclose the code below in a </form> element, the drop-down menu collapses. <h5>Advanced with Templating, Filtering and Clear Icon</h5> <p-dropdown [options]="countries" [(ngModel)]=& ...

What is the best way to get my Discord bot to respond in "Embed" format using TypeScript?

I've been attempting to create a bot that responds with an embedded message when mentioned, but I'm running into some issues. Whenever I run this code snippet, it throws an error in my terminal and doesn't seem to do anything: client.on(&apo ...

What is the best way to extract value from subscribing?

I attempted to accomplish this task, however, I am encountering issues. Any assistance you can provide would be greatly appreciated! Thank you! export class OuterClass { let isUrlValid = (url:string) => { let validity:boolean ...

What could be causing the absence of data from my API on my HTML page?

I've been working on fetching data from my database using an API in Angular, but I'm facing an issue where the data is not being displayed on the HTML component. Although I can see that the data is being fetched through the console and the HTML p ...

Creating a Docker Image for Node.Js Using Bazel

Reason Behind the Need I am diving into the Bazel world and struggling to find comprehensive references on constructing Docker images for Node.js. My focus lies on a Typescript-based Node.js application that relies on two other Typescript packages. My ul ...

transferring libraries via functions in TypeScript

As I work on developing my app, I have decided to implement the dependency-injection pattern. In passing mongoose and config libraries as parameters, I encountered an issue with the config library. Specifically, when hovering over config.get('dbUri&ap ...

Developing a databound listview in Ionic: A step-by-step guide

In the world of programming, each platform has its own way of handling lists. For example, Android uses RecyclerView, WPF uses ListView, and in Ionic, we have ion-list. If you have a list of strings like this: Animals:string[] = ["Dog", "Cat", "Human", "C ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Is there a way to stop PrimeNG Tree onNodeSelect() event from triggering when utilizing templating?

How can I prevent a PrimeNG Tree with templating from selecting/deselecting the node on any click inside the template? Specifically, I want only a click on the <a> element to call doSomething(), not nodeSelected() as well. Here is the code snippet: ...

Printing with Angular 2+ using ngx-print extension can be done manually by

Is there a way to print a div in Angular +2 using ngx-print, without automatically triggering the print function through a button attribute like ngxPrint? <button printSectionId="print-section" (click)="printProcedure()">print</button> ...

Utilizing the ternary operator in Angular HTML templates

Using the ternary operator in HTML can simplify your code: <div> {{ showStringOneFlag ? 'Display String 1' : 'Display String 2' }} </div> This approach could save you from setting a string variable multiple times in JavaSc ...

Personalizing Dialog Title in material-ui

While delving into the world of React and Material-UI, I encountered a challenge in updating the font color in the DialogTitle component. After browsing through various resources, I came across a helpful link that suggested overriding the dialog root class ...

ng-module with tabbed content

I am facing a unique scenario where I have a UserProfileComponent with a tab structure and I want to add tabs from different modules. UserProfileComponent.html <ngb-tabset> <ngb-tab> <app-user-profile-history></app-user-prof ...

Using mergeMap in conjunction with retryWhen allows for the resumption of retries from the exact point of failure, without needing

I have a list of URLs, the number of which is unknown until it stops (depending on some condition). This is how I am currently using them: from(observableUrls) .pipe( mergeMap(url => callHttpService(url) , 4), retryWhen( // Looking f ...

Is there a way to obtain an array after subscribing to an RxJS method?

I am struggling with the following code snippet: Rx.Observable.from([1,2,3,4,5,6]) .subscribe(x=>console.log(x)); Is there a way to modify this code so that instead of iterating through the array elements from the .from() method, I can return the enti ...