Managing large objects in Angular (type safety and more)

When using http, I receive an array of large objects with many values, some of which are irrelevant to me.

The object (represented as ...) looks like this:

id: '45678',
attributes: {
  title: 'This is a title!'
  ...
},
resources: [
  {url: 'www.facebook.com', type: 'social media', ...},
  {url: 'www.instagram.com', type: 'social media', ...},
],
...

If I have a component that needs to display specific values from the object and ignore the rest (...), what would be the best approach?

Should I create a new array, map the original one, and only push a modified object with the necessary data? Also, when it comes to typing and creating interfaces in Angular, do I need to define all objects?

EDIT:

return this.http.get(this.url)
  .pipe(
    map((a: any) => {
      const products = [];
      a.items.map(obj => {
        products.push({id: obj.id, resources: obj.resources, attributes: obj.attributes});
      })
      return products;
    })
  );

Answer №1

When working with the Angular HttpClient, it is common to receive an

Observable<YOUR_OBJ_TYPE[]>

To manipulate the array objects, you can utilize the rxjs map operator in the following manner:

httpClient.get<YOUR_OBJ_TYPE[]>('URL')
     .pipe(map((res:YOUR_OBJ_TYPE[])=> res.map(
      (obj: YOUR_OBJ_TYPE) => {
        id: obj.id,
        attributes: obj.attributes,
        resources: obj.resources,
        ...
})))

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

Storing Bearer Tokens in Angular from Response Headers

After sending a login post request, I received a response. Everything looks good except the fact that the response body is empty and I am unsure how to access (and store locally) the Bearer token. Currently, this is what I can log: https://i.sstatic.net/N ...

Compiler unable to determine Generic type if not explicitly specified

Here is a simple code snippet that I am working with: class Model { prop1: number; } class A<TModel> { constructor(p: (model: TModel) => any) {} bar = (): A<TModel> => { return this; } } function foo<T>(p: ...

Encountered an issue in React and Typescript where the argument type is not compatible with the parameter type 'EventListenerOrEventListenerObject'

One challenge I am facing is integrating Typescript into my React project: componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); } private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => { appS ...

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 ...

Merge obs with a variety of filtering choices

I have the following scenario Fetch data if it hasn't been retrieved yet this.mailFacade.mailLoaded$ .pipe( filter(res => !res), takeUntil(this.unsubscribe$) ) .subscribe(_ => this.mailFacade.get()); this.use ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Testing Next.js's getServerSideProps function with Jest: A Step-by-Step Guide

I want to conduct Jest and Enzyme tests on the Next.js getServerSideProps function. This function is structured as follows: export const getServerSideProps: GetServerSideProps = async (context) => { const id = context?.params?.id; const businessName ...

What is the best way to create a calendar that displays every day in a single row?

Is it possible to create a calendar with all days in one row? I've been searching for a solution to this problem without any luck. It's surprising that I haven't found a clear answer or explanation on how to achieve this. I'm sure man ...

Utilize Material icons in CSS for a list in Angular 9

My task involves altering the HTML provided by a content management system for one of our applications. Specifically, I need to replace all "ul"s with <mat-icon>check_circle_outline</mat-icon> instead of the default "." The challenge lies in t ...

NodeJs backend encounters undefined object due to FormData format request sent from Angular frontend

Never encountered this issue before despite having used this method for a long time. (Angular Frontend) const myFormData = new FormData(); myFormData.append("ok", "true"); this.http.put(my_Express_backend_url, myFormData); (Express ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

Encountering an issue where the module '@angular/compiler-cli/ngcc' cannot be located in Angular 8

Upon attempting to run ng serve from my terminal window, I encountered the following error: An unhandled exception occurred: Cannot find module '@angular/compiler-cli/ngcc' Here is an excerpt from my package.json file: { "name": "ProjectDeta ...

A mistake was made: The template contains errors stating that 'app-my-profile' is an unknown element

I encountered an error message: "Uncaught Error: Template parse errors: 'app-my-profile' is not a known element," while working on setting up my profile service. import { BrowserModule } from '@angular/platform-browser'; import { NgM ...

What is the process for creating a class in TypeScript?

Here is an example of the object structure I am working with: { "info" : { "title" : '123}, "details": [ {"desc": "d1"}, {"desc": "d2}] } I am currently in the process of defining ...

Clear function of signature pad not working inside Bootstrap modal dialogue box

Currently, I'm working on implementing a signature pad dialogue box using Bootstrap modal. When the user clicks on the "Complete Activity" button, a dialog box should pop up with options for yes or no. If the user selects yes, another dialog box shoul ...

I can't seem to understand why the error "bash: ng: command not found" keeps popping up even though I

Ever since I installed Angular CLI and started working with Angular, something strange happened - the ng command suddenly became not found: ng serve -o Here's a screenshot for reference: bash: ng: command not found Oddly enough, when I use the npx c ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

Showing elapsed time similar to YouTube in an Angular 8 application

Currently, I am developing an Angular application to replicate certain features found on YouTube by utilizing data fetched from an API. This API provides video timestamps in a string format Each timestamp follows this structure : YYYY-MM-DDTHH:MM:SS For ...

Is it possible to navigate to the Angular component that defines a tag in VSCode by simply clicking on the tag?

In my current Angular project in VSCode, I often find myself wanting to delve deeper into specific tags that I encounter while coding. For instance, if I stumble upon a tag like <display-active-users>, I usually have to go through the process of sea ...

How can you detect when a user clicks outside of a bootstrap modal dialog in Angular?

Is there a way to detect when a user clicks outside of a Bootstrap modal dialog? <!-- EXPANDED MODAL --> <div class="modal fade" id="itinerary" tabindex="-1" role="dialog" aria-labelledby="modal-large-label"> <div class="modal-dial ...