Setting property values in Typescript by initializing them from other properties when reading objects from a subscription response

I have created a basic class structure

export class SampleObj{
  item1: string;
  item2: string;
  item3: string;
}

I am fetching data from the backend and populating this class using HttpClient:

this.httpClient.get<SampleObj[]>(`backendUrl`).subscribe(
  (response: SampleObj[]) => {
    //...additional code...
  }
);

Now, I want to add a new property item4 in this class that will be initialized based on other properties during instantiation and should be accessible in the returned response. I attempted to modify the class definition as shown below but encountered an issue. How can I achieve my desired outcome?

export class SampleObj{
  item1: string;
  item2: string;
  item3: string;
  item4: string;

  constructor(item1, item2, item3) {
    this.item1 = item1;
    this.item2 = item2;
    this.item3 = item3;
    this.item4 = item1 + item2 + item3;
  }
}

Answer №1

In my opinion, it would be beneficial to define the raw ApiResponse separately from the MyObj class:

interface ApiResponse {
  prop1: string
  prop2: string
  prop3: string
}

class MyObj {
  prop1: string
  prop2: string
  prop3: string

  // additional properties
  prop4: string

  constructor(rawResponse: ApiResponse) {
    this.prop1 = rawResponse.prop1
    this.prop2 = rawResponse.prop2
    this.prop3 = rawResponse.prop3

    // additional properties
    this.prop4 = rawResponse.prop1 + rawResponse.prop2 + rawResponse.prop3
  }
}

Following the API request, proceed with parsing and potentially validating the response data:

get<ApiResponse[]>('https://www.example.com')
  .subscribe((response) => {
    const myObjs = response.map(x => new MyObj(x))

    // perform actions using myObjs
  })

Answer №2

Attempt using

Object.assign(this.data, this.info1, this.info2, this.info3);

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

Utilizing React TypeScript within Visual Studio

Utilizing the most recent editions of Visual Studio and Visual Studio Code, I have initiated a project using create-react-app with TypeScript react scripts version. My objective is to host my project within a .NET Core web application that I've estab ...

How can I retrieve user group information from Keycloak in my Angular application?

While it is common knowledge that Keycloak stores user information in local storage for easy access to username and email, I am curious about how to retrieve details regarding the group(s) a user is associated with. Can anyone provide insights on this? ...

Storing a variable in Cypress with Typescript for use in the afterEach teardown step

Throughout my test cases, I store data in a variable to be used consistently. The variable maintains its value until the very end of the test, but when trying to access it in the @afterEach teardown function for global clean up, it appears empty. It seems ...

Typescript TypeError: Unable to call function this.array[i].greet as it is not defined

When attempting to call my function, I am encountering an error. Interestingly, everything works fine when I create just one object of someClass and then utilize the greet function. This is what does not work (someArray being an array of type someClass): ...

Using the Ngclass function with a pair of objects

Can you include 2 objects in an ngclass function like this? <div class="progress-bar"[ngClass]="getProgressValues(obj.val1,obj.val2)"> </div> I am encountering a JSON error. SyntaxError: JSON.parse: bad control character in string literal at l ...

Using TypeScript with React - employing useReducer with an Array of Objects defined in an Interface

After implementing the given component, I encountered an error related to my useReducer function. The specific error message states: "No overload matches this call..." and provides details on how the parameters are not compatible. import React, {useReducer ...

Angular 13: How to Handle an Empty FormData Object When Uploading Multiple Images

I attempted to upload multiple images using "angular 13", but I'm unable to retrieve the uploaded file in the payload. The formData appears empty in the console. Any suggestions on how to resolve this issue? Here is the HTML code: <form [formGro ...

Obtaining user profile pictures from Graph API for several users at the same time with the help of RxJs

I have created an ASP.NET Core API that can provide a list of users to an Angular service. The user data returned consists of certain properties like id, firstName, and lastName. My aim is for the Angular service to first fetch this user list from my API ...

Displaying a child component as a standalone page rather than integrating it within the parent component's body

I'm currently working on implementing nested navigation in my website, but I am facing challenges with loading the child component without the need to include a router-outlet in the parent component. This setup is causing the child component's co ...

Typescript: The property 'userId' is not found within the 'unknown' type

For my rxJS practice in Typescript, I wrote the following simple code. import fetch from 'node-fetch'; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from &apo ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...

The 'GoogleAuthProvider' property cannot be found on the 'AngularFireAuth' type

When attempting to sign in with Google using 'AngularFireAuth', I encountered an error. Here is the code snippet from my auth.service.ts file: import { Injectable } from '@angular/core'; import { first } from 'rxjs/operators'; ...

Leveraging data from a service in Angualr 5 within createServerRenderer

I am currently utilizing the .Net Core Angular CLI based template available at this link. When it comes to server side rendering, this template generates a crucial file named main.server. import 'zone.js/dist/zone-node'; import 'reflect-me ...

What steps can I take to make sure that the asynchronous initialization in the Angular service constructor has finished before proceeding?

Hello experts, can you advise on ensuring that asynchronous initialization in the service constructor is completed before calling other functions within the class? constructor() { var sock = new SockJS(this._chatUrl); this.stompClient = Stomp.ov ...

Managing the sequence of observable requests

One of the services I provide involves conducting validation checks before sending a request to my backend server. fetchData(systems?: string[], options?: {}): Observable<System[]> { if ( // check cache ) { // validate option ...

Challenge with JWT Tokens

In my application, I am utilizing a Node.JS express backend along with an Angular 4 frontend. The user ID is stored in JWT tokens, which do not expire. Here is the scenario: The user logs in. A JWT Token is generated and signed (containing the user ID). ...

Firestore data displaying as null values

Recently, I encountered CORS errors while polling the weather every 30 seconds in my program. Upon investigating, I discovered that the city and country were being interpreted as undefined. To fetch user data from my users' table, I utilize an Axios ...

Unusual behavior of Typescript with Storybook's addon-docs

I'm trying to integrate storybook addon-docs into my TypeScript React project. Everything seems to be almost working, but I've noticed that the file name is affecting how the props type table gets rendered. Here is my file structure: src - Butto ...

What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful. Here ...