Using Angular, we can make an HTTP call and map the response to an

I have a function that fetches information from a REST API in this format:

getProducts(category: string): Observable<IProduct[]> {
    let url = `/rest/getproducts?category=${category}`;
    return this._http.get<IProduct[]>(url);
  }

The data returned by the service is structured like below:

[
  {
    "ProductId": 1,
    "CategoryType": "XC",
    "Name": "Prod A"
  },
  {
    "ProductId": 2,
    "CategoryType": "XY",
    "Name": "Prod B"
  },
]

This is how my model is defined:

export interface IProduct {
    id: string;
    type: string;
    name: string;
}

Is there an easy way to map the response from the service to fit my model structure? Should I use the map function for this task? While I can adjust the model to match the response, I prefer to find a way to adapt the response to fit my existing model (the example provided has been simplified).

Answer №1

Opting for an interface that mirrors the server data structure can streamline the process, eliminating headaches associated with mapping and reducing maintenance requirements.

It's advisable to still create an interface for the server object even if some mapping is necessary to ensure safe data manipulation:

interface IServerProduct {
    "ProductId": number;
    "CategoryType": string;
    "Name": string;
}

export interface IProduct {
    id: string;
    type: string;
    name: string;
}

getProducts(category: string): Observable<IProduct[]> {
    let url = `/rest/getproducts?category=${category}`;
    return this._http.get<IServerProduct[]>(url).pipe(
        map(o => o.map((sp): IProduct => ({ // Defining IProduct here triggers excess property checks
            id: sp.ProductId + '', // Transforming number from server into string 
            name: sp.Name,
            type: sp.CategoryType,
            typeMisaken: sp.CategoryType, // Potential error flagged here
        })))
    );
}

Answer №2

If you prefer not to make any changes to the code, your interface should resemble the example below. Alternatively, you can use the array.map function to create your own array.

declare module namespace {
    export interface IProduct {
        ProductId: number;
        CategoryType: string;
        Name: string;
    }
}

If you'd like to see how it looks without altering anything, you can try using json2ts

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

Utilize the array map function in a React Native functional component with useState to dynamically render content

I have successfully implemented a functional component that renders a basic form with input elements. My goal is to allow users to dynamically add input elements by clicking a button. To achieve this, I am utilizing the useState hook and have created an o ...

NextJS: Build error - TypeScript package not detected

I'm facing an issue while setting up my NextJS application in TypeScript on my hosting server. On my local machine, everything works fine when I run next build. However, on the server, I'm encountering this error: > next build It seems that T ...

Struggling to access the production API results in a frustrating 404 error

I'm currently facing an issue with deploying my website as the API call is not functioning properly. Specifically, I am receiving a 404 not found error message. Here is the structure of my project: . After running npm run build, this is how my nex ...

Ways to initialize Nested Arrays in Angular applications

I have been experimenting with some code on Codepen. I am trying to load JSON data from a service and then use ng-repeat to display the arrays. The issue I'm facing is that while the first array loads successfully, the nested array "data.cities" is n ...

Module 'fs' or its type declarations could not be located

I am facing an issue with TypeScript not recognizing the 'fs' module. The error I receive is as follows: Error: src/app/components/drops/drops-map/drops-map.component.ts:9:29 - error TS2307: Cannot find module 'fs' or its correspond ...

Creating a comprehensive object within a single interface using Typescript

Here is an example of an Object in TypeScript: export class test{ recordname: string; comments: [{ comment: string }] } To define it using one interface instead of multiple interfaces, you can try something like this: export int ...

Angular Directive for dragging and dropping elements within an iFrame

Looking for controls to enable Drag & Drop functionality across an iFrame? The reason for needing this capability within an iframe is due to building a CMS where any "absolute" css changes on the editing page will also affect the main site. I have develop ...

Why is my specified state not being recognized?

Having trouble with my code here. Every time I try typing "localhost:3000/page1", I keep getting an error message saying "cannot get /page1". Here's the code snippet that I'm working with: var module = angular.module('ngFirstApp',[&apo ...

The benefits of a modular design in a React and TypeScript library

Following a tutorial on creating a library with React, Typescript, and rollup, I successfully managed to get everything working. However, as my project grows with additional features, I'm looking to have modular exports similar to what is seen in redu ...

Utilizing a class member's data type

I need to inform Typescript that a member of my class is derived from another class. For instance: Class Main{ getDataFromChild(data){ console.log(data) } } Class Child{ getDataFromChild: Main.getDataFromChild } Scenario Application In my s ...

Invoke the LazyQuery Hook within a Function

My GraphQL query implementation is as follows: const [loadUsers, { loading, data }] = useLazyQuery(LoadUsersQuery); When I utilize this code snippet in my project, the lazy query loadUsers functions properly and displays the results: return ( <d ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

How does Jasmine compare to the second parameter with the toBeCloseTo function?

Jasmine's documentation is often brief, but not always sufficient. I am curious about the second parameter of the toBeCloseTo function. The official reference only provides this example: it("The 'toBeCloseTo' matcher is for precision mat ...

TypeScript: implementing function overloading in an interface by extending another interface

I'm currently developing a Capacitor plugin and I'm in the process of defining possible event listeners for it. Previously, all the possible event listeners were included in one large interface within the same file: export interface Plugin { ...

What is the best way to fetch information from an external json api using angularJS?

As an example, I am interested in accessing data from two different URLs: 1- http://jsonplaceholder.typicode.com/posts/ 2- http://jsonplaceholder.typicode.com/todos/ Is it possible to fetch data from these two URLs in a single application using two contro ...

Toggle checkbox feature in Bootstrap not functioning properly when placed within ng-view

When attempting to embed a bootstrap toggle checkbox within <ng-view></ng-view>, an issue arises where a regular HTML checkbox is displayed instead of the expected bootstrap toggle. Strangely, the same checkbox functions as a bootstrap toggle w ...

Using AngularJS for client side validation and Asp.net MVC for server side validation

When it comes to using Angularjs with Asp.net MVC, as a newcomer in the world of Angularjs, I am encountering some challenges integrating it with MVC. Currently, my focus is on validating a form, utilizing: 1. For client-side: Angularjs 2. For server-sid ...

Preparing data for posting in AngularJS is crucial for ensuring proper formatting of the content

I am trying to figure out how to send my cartPost post data in the following format: products= [ { "code": "mig-09", "title": "supermig", "quantity": "1" } ] Below is the code for my http.post $http.post("www.remoteurl.com", { pro ...

Strategies for extracting information from JSON data and presenting it using AngularJS

I am trying to display a name in string format on the Main.html page, but it seems that the page is not reading the value from the session.json file. Can anyone assist me with this? var app = angular.module('angularjs-starter', []); app.co ...

Angular's vs-repeat continues to fire scroll events until it reaches the bottom, occasionally also triggering events when it

One of my pages has a strange issue where the scroll-down event seems to be duplicated every time vs-repeat finishes and triggers the $digest until it reaches the bottom. The repeat statement is quite messy. <div vs-repeat class="code-window" ng-init=" ...