Generating an Object Using HttpClient

When working with httpclient, you can specify the type for the get call and receive a struct of that object. For example.

http.get<ProductData>("url:ressource:id").subscribe(x=> this.myObj = x)

This means that myObj will only appear to be the type of the object. If I have functions on that object, they are not callable. So, I understand that I need to create a new Object and assign the properties of the result of the request to it. My question is, can we have a function that takes a type as a Template and then returns an observable of that type with an instance?

something like this

http.get<ProductData>("url:ressource:id").makeNew<Product>()
where the result of makeNew would be an observable of type Product, so when you subscribe to it, you would get a Product.

I believe a simpler way to think about it can be seen in this example.

this.http
.get<IProduct>('https://dummyjson.com/products/1')
.pipe(
  map((x) => {
    var a = new ProductDisplay();
    Object.assign(a, x);
    return a;
  })
)
.subscribe((x) => {
  console.log('obj is ', x);
});

Is it possible to replace the .map portion with one function call like makeNew<Product>()

Answer №1

If you want to simplify the process of creating instances of a class, consider creating your own operator to handle it for you.

export const createInstance = <T>(clazz: new () => T) => map(x => Object.assign(new clazz(), x));

This custom operator can be used in a single line within your pipe function:


...
get<...>(...).pipe(
  createInstance(ProductDisplay)
)

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

Changes in the styles of one component can impact the appearance of other

When it comes to styling my login page, I have specific stylesheets that I include in login.component.ts. For all the common CSS files, I have added them in the root index ("index.html") using the traditional method. However, after a user logs into the sys ...

The querySelector function in an Ionic page built with Angular may require a timeout for proper

This example demonstrates two different approaches: ionViewDidLoad() { var that = this; setTimeout(function () { that.img = that.el.nativeElement.querySelector('.user-image'); alert(that.img.src); ...

Unable to locate the module '@vitejs/plugin-react' or its associated type

After creating the project with npm create vite@latest and selecting ts-react, everything seemed to work fine when I ran npm run dev. However, in my vs code editor, I encountered the error message "Cannot find module '@vitejs/plugin-react' or its ...

Angular 8 and Bootstrap 4 Integration: Navbar Functionality Working, but Issue with Auto-Closing on Click Action (Both Inside and Outside Navbar)

While using ng-bootstrap with Angular 8, I encountered a problem with the navbar. The navbar functions properly by being responsive and opening/closing when clicking the hamburger icon. However, the issue arises when it does not automatically close when a ...

A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this? HTML: <mat-form-field> ...

What security measures does Angular implement to safeguard against malicious user input?

While I was learning how to build a router in vanilla JS, the tutorial author mentioned that it's advisable to use frameworks like Angular or React for various reasons. The author pointed out that Angular, for example, sanitizes user input before inse ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Creating an array of objects in Angular 2

I'm facing an issue with the following expression: public mySentences:Array<string> = [ {id: 1, text: 'Sentence 1'}, {id: 2, text: 'Sentence 2'}, {id: 3, text: 'Sentence 3'}, {id: 4, text: 'Sen ...

Do I need to be concerned about a bot attack if my form does not submit to a specific endpoint in a single-page application (SPA)?

My latest project involves a form with fields for email and password, but instead of POSTing the data, it simply calls a function upon submission. Although I'm using Angular, I wonder if I should be worried about potential bot attacks. Do you think I ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Creating a Dynamic Download Link in Angular 6

Hello everyone, I need assistance in making my download feature dynamic. Here is my HTML code: <button class="btn btn-primary" (click)="downloadMyFile({{account.students[0].schoolId}})"><i class="fa fa-file-pdf-o"></i> Download</butt ...

Ngrx effects are not compatible with earlier versions of TypeScript, causing issues with functionality

Seeking assistance with my Ionic 3 App utilizing ngrx/store and ngrx/effects. However, upon attempting to run the app, I consistently encounter the following error: TypeScript Error A computed property name in a type literal must directly refer to a bui ...

Using Angular 5 for sending HTTP POST requests with x-www-form-urlencoded content-type

Currently, I have been immersing myself in Angular and am nearing completion of my initial end-to-end application. This specific app is designed to interact with Spotify's public API in order to search for music and play track previews. The primary i ...

Accessing nested JSON objects with key-value pairs

I have a method in my .ts file that displays keys but doesn't fetch nested JSON data. generateArr(obj) { return Object.keys(obj).map((key) => { console.log(key, obj[key]); return {key: key, value: obj[key]}; }); } Here is the HTML code I&apo ...

Tips for transitioning from Angular 4 to Angular 5

As a newcomer to Angular, I recently launched a project using Angular CLI. However, a new version has been released since then. I am looking to update my project to the latest version of Angular (v5). How should I go about migrating it? ...

Having trouble accessing @ViewChildren from the parent component

I've been facing an issue while attempting to control the child instances of a component and I can't seem to bypass this particular error. I've been referring to solutions provided on this specific thread. The main component Sequence houses ...

Why does my Observable remain perpetually unfulfilled?

I recently started learning javascript and came across the Angular 2 Documentation where I discovered that Promises can be replaced with Observables. While experimenting with a simple code, I noticed that in addition to the expected result, I am also getti ...

Issue with Typescript in Material-UI's CardActionArea component attribute

The documentation for Material-ui's Buttons | Third party routing library explains the need to create an adapter to wrap a react-router-dom/Link component in a Button. Interestingly, attempting the same with a CardActionArea (which is labeled as a Bas ...

Step-by-step guide on crafting a personalized button component in Angular 2 and above with the help of ControlValueAccessor

Are you looking to create a custom button component in Angular versions 2 and above using ControlValueAccessor? Do you need help handling click button and focus events within your custom button? Check out the following sample code: import { Component, OnI ...