What is the most effective method for retrieving specific data fields from large datasets received from a RESTful service in Angular?

When calling a RESTful service that returns data with many fields, I needed to create an interface similar to a DTO to only carry the necessary data. To achieve this, I utilized pipe & map from rxjs, but I am unsure if this is considered best practice:

The usual returned data:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aaf9c3c4c9cfd8cfeacbdad8c3c684c8c3d0">[email protected]</a>",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {...}
]

The data I need:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9ead0d7dadccbdcf9d8c9cbd0d597dbd0c3">[email protected]</a>"
  },
  {...}
]

User Interface:

export interface User {
    id?:number,
    name?:string,
    email?:string,
    username?:string
}

User Service:

export class UsersService {
  constructor(private http: HttpClient) {}

  getAllUsers(): Observable<User[]> {
    return this.http.get<User[]>("https://jsonplaceholder.typicode.com/users")
      .pipe(
          map((data: User[]) =>
              data.map((item: User) => {
                return {
                  id: item.id,
                  name: item.name,
                  email: item.email,
                  username: item.username,
                };
              })
          )
      );
  }
}

Answer №1

I have discovered the solution:

User Interface Examples:

interface Person {
  id: number,
  name: string,
  email: string,
  username: string
}

interface UserInformation {
  id: number;
  name: string;
  username: string;
  email: string;
  address: any; // using 'any' as a placeholder
  phone: string;
  website: string;
  company: any; // also using 'any' as a temporary option
}

User Service Class:

export class UserService {
  constructor(private http: HttpClient) { }

  fetchData(): Observable<Person[]> {
    return this.http.get<UserInformation[]>('https://jsonplaceholder.typicode.com/users')
      .pipe(
        map((data: UserInformation[]) =>
          data.map((item: UserInformation) => {
            return <Person>{
              id: item.id,
              name: item.name,
              email: item.email,
              username: item.username,
            };
          })
        )
      );
  }
}

Example on Stackblitz

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

Error: `target` property is not recognized on `htmlelement` type

I am attempting to retrieve the ID of a list item in a select menu but I am having trouble getting the value from it. The value should be a number. HTML File <div class="form-group mt-3"> <label class="form-label">Produc ...

Is there a TypeScript type that represents a subset of the keys of another type?

When given an object, is it possible to create a second typed object that contains only a subset of the original keys with different value types? I attempted to use Partial<keyof ...>, but it did not have the desired effect. Is there another approach ...

Autocomplete search from a distance

I am currently learning Angular and trying to create an autocomplete form with content that is filtered on the back-end. I have defined a class and Interface for Terminal: export class Terminal { constructor( public id: number, public name: ...

Assigning a type of Undefined to type [Film] is invalid

Currently, I am in the process of learning how to make HTTP requests in Angular using services. Below is a snippet of my code: export class ApiCallService { // DECLARATIONS: tmdb_api_key = '*******'; // personal api key to access the TMD ...

Trying to find a more efficient method to export multiple classes as an array in typescript

I've organized my files like this: index.ts folder/ a.ts b.ts subfolder/ c.ts d.ts e.ts ... In each file, there is one default exported class and I want index.ts to export all these classes as an array. Currently, I achieve thi ...

Visual Studio Code is encountering issues when trying to start a Node application

I am in the process of setting up a workflow for an express app using TypeScript, Visual Studio Code, and gulp. Here is the structure of my project: src/ <-- source files Start.ts Server.ts models/ Contact.ts Organization.ts bin/ <- ...

Is there a way in Typescript to filter for the first instance of a unique object in an array of objects?

Having an array of JSON objects like this, the task is to iterate through it and retrieve the first occurrence of 'appname', such as 'app1' or 'app2', and store the entire object for each... myArray[ { ...

What is the process for configuring NextJS to recognize and handle multiple dynamic routes?

Utilizing NextJS for dynamic page creation, I have a file called [video].tsx This file generates dynamic pages with the following code: const Video = (props) => { const router = useRouter() const { video } = router.query const videoData = GeneralVi ...

Issue with Promise.race not resolving inside useEffect hook in React Native application

I am currently implementing a progressive image loader, which involves downloading and replacing an image with increasing quality. Initially, I perform a cache check to determine if the desired image is already cached. While this check is being carried out ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

Encountered an error while trying to upgrade Angular from version 9 to 10: The package '-e' is not recognized as a dependency

Anyone else run into this problem while upgrading an Angular app from version 9 to 10? The error message reads: ng update @angular/core@10 @angular/cli@10 I tried searching online but couldn't find any solutions that addressed my specific issue. ...

Angular Material Stepper Design Styling Guide

https://i.sstatic.net/8R93n.pnghttps://i.sstatic.net/VxzP3.png Hello, I am interested in customizing the angular material stepper UI similar to the image provided. I would like to know if it is possible to programmatically change the icon. In case of an e ...

Hold on for the processing of a CSV document

I am attempting to utilize the "csv-parse" library in Typescript to read a csv file by creating an observable. The code provided uses fs.createReadStream to read the file. I am looking to return the observable and subscribe to it, but it seems that the p ...

Utilizing HTTP request headers in Angular 6

Recently starting out with Angular, I've been working with the latest version. My current challenge involves executing a post request but I keep encountering a CORS issue. I suspect that the problem lies in the absence of a content type in my request ...

Angular 2 (stable) is experiencing issues when attempting to route with an outlet and a non-empty path

A route in Angular2 uses the following router path: { path: 'lefttoggle', redirectTo: 'lefttoggle', pathMatch: 'full', outlet: 'lefttoggle_name'}, An exception is being thrown when this route is accessed. Edit: ...

"Although Protractor is able to locate an element, invoking the .click() method results in the element not being

Encountering an issue where the xpath shows zero errors on the test script when using .isPresent(); to confirm the presence of the element, but throws errors indicating the xpath cannot be found when attempting a "click" command instead. Here is the xpath ...

Accessing elements from a JSON array in Angular 4

Currently working on an Angular 4 app with two components/pages. The first component is associated with object id:1, occupying one page, while the second component is linked to id:2 and occupies another page. Both of these pages share a common template nam ...

Angular submission triggered a SuspiciousFileOperation error at /media/C:/fakepath/example.png

Currently working on a project that combines Angular and Django features, allowing users to upload files to a model: Model: def upload_path(instance, filename): return '/'.join(['files', str(instance.title), filename]) class File ...

When I execute the ng build --prod command, the (activate) event in the <router-outlet> does not function as expected

I usually don't have any issues with my code - when I execute ng build, everything works smoothly, and the event (activate) is triggered. However, when I run ng build --prod, this event does not seem to fire. Why could this be happening and how can I ...

What causes me to create components with incorrect paths?

Can someone assist me with creating a new component in the dynamic-print folder instead of it being created in the app? Thank you ...