Acquiring the class function from a service which yields a model

Within my class called userName, I have defined properties that form a model when casting from json. Additionally, this class includes a simple function that returns the full Name:

export class userName {
    firstName: string;
    lastName: string;
    get fullName() {
     return `${this.firstName} ${this.LastName}`
    }

In my service, I have a method that retrieves a collection of users:

getUsers() : Observable<userName[]>
{
 return this.http.get<userName[]>(<path>);
}

After retrieving the collection from the service in the component, I want to display the firstName + LastName together like the fullName property does, even though it is not returned by the service. Is there a way to achieve this without creating a custom extension?

Answer №1

Utilize the map function when dealing with an object retrieved from a service:

getUsers().pipe(    
    map(user => users.map(user => {
       return {
         firstName: user.firstName,
         lastName: user.lastName,
         fullName: user.firstName + user.lastName   
   }))
);

Answer №2

Category:

export class User {
  firstName: string;
  lastName: string;
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  constructor(firstName: string, lastName: string) {
    Object.assign(this, { firstName, lastName });
  }
}

Function:

retrieveUsers() : Observable<User[]> {
    return this.http.get<User[]>(<url>).pipe(map((user: User) => new User(user.firstName, user.lastName)));
  }

Answer №3

Enhance userName class with a new constructor method:

export class userName {
    firstName: string;
    lastName: string;
    get fullName() {
     return `${this.firstName} ${this.LastName}`
    }

    constructor(jsonObject = {}) {
      this.firstName = jsonObject.firstName ? jsonObject.firstName : null;
      this.lastName  = jsonObject.lastName ? jsonObject.lastName : null;
    }
}

Utilize the http observable response and map it to your custom object

this.usersService.getUsers()
  .pipe(
    map(res => {
      return res.map((item) => new userName(item));
    })
  )
  .subscribe(users => {
    // console.log(users[0].fullName)
  })

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

What is the best way to use jQuery to set the height of one div equal to another div

Edited: I am facing a situation with a 3-column layout - Column A, Column B, Column C. The height of Column A is dynamic and I need to set the same height for both Column B and C. For instance, Column A contains a tabbed panel with varying heights based ...

Issues with debuggers in Chrome and Firefox with AngularJS are causing frustration for developers

Currently, I am in the process of developing a hybrid application that combines AngularJS with Angular 8. As part of my testing procedure, I am attempting to debug the application. However, I have encountered an issue where the debuggers function properly ...

Error encountered while rendering HTML template with Django and AngularJS due to TemplateSyntaxError

Hello, I am new to Angular and Django. I have built a Django webpage and am attempting to display values from a basic AngularJS app and controller tutorial using my HTML template. However, I keep encountering an error in the index.html file when trying to ...

How can a JQuery slideshow be programmed to only iterate once?

Looking to create a slideshow that transitions between images every two seconds? Check out the code snippet below: HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" ...

Ways to populate an Angular Material chips array during initialization

I am struggling to implement "angular-material chips with form control" as I need to keep track of the selected chips. Currently, I am unsure how to initialize both the FormControl and Set constructor with a string array. Below is my code/class: export cla ...

What is the best way to retrieve scope variables from multiple directives?

I am working on a directive that represents a person with changing location attributes. My goal is to access all the locations together and plot them on a map using the angular-leaflet-directive. I'm struggling to figure out how to access these variab ...

I am facing an issue with the Tailwind Flowbite Datepicker dropdown UI when running "npm run prod" for minification. The class is not being added during minification on the npm

I have successfully integrated a Laravel project with Tailwind CSS. I have also implemented the Flowbite Datepicker using a CDN to include the necessary JavaScript. Initially, everything was working fine and the date-picker was displaying correctly. Howev ...

Angular is a powerful framework that enables the creation of dynamic user interfaces. One of its many

Looking to implement a Material table with expandable rows in Angular. table-tree.html <table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8" > <ng-container matColumnDef="{{co ...

Angular - Set value only if property is present

Check if the 'rowData' property exists and assign a value. Can we approach it like this? if(this.tableObj.hasOwnProperty('rowData')) { this.tableObj.rowData = this.defVal.rowData; } I encountered an error when attempting this, specif ...

Tips for showing/hiding textboxes based on select options:

I am currently working on a project that allows users to enter their personal information. I need help figuring out how to show or hide textboxes based on the selection made in a dropdown menu. The dropdown menu in question is for marital status. The opt ...

Avoid inputting numbers and special characters

In my coding work, I have crafted a function that detects the key pressed by the user through an event. NameValidation(e){ if(!e.key.match(/^[a-zA-Z]*$/)) { e.key = ''; console.log(e.key); } }, This function essentia ...

Is there a distinction in functionality when utilizing fat arrow syntax versus traditional syntax for ES6 class methods and React?

Consider these two examples showcasing different ways to write an ES6 class method: The first example uses the non-fat arrow, or concise method syntax: class Test extends Component { handleClick() { return 'clicked' } } The second exam ...

Combining selected boxes through merging

Looking to create a simple webpage with the following requirements: There should be 10 rows and 3 boxes in each row. If I select 2 or more boxes or drag a box, they should merge together. For example, if my initial screen looks like this: and then I se ...

Steps for setting the keys of a map as a priority when initializing a state variable in Typescript for a React component

I am working with a state variable that connects a string username to a UserData object. Initially, the usernames are stored in the string array 'users'. Is there a method to assign the initial state of 'userDataMap' with the keys fro ...

Having Difficulty Applying a Background Color to a Class in Bulk

I am working on a unique HTML canvas for pixel art, which is created using a table made up of various divs all sharing the "pixel" class. I want to add a clear button that can reset the entire canvas, but changing the background color of each individual di ...

Validation of Button Groups and Automatic Disabling after Initial Click with HTML, CSS, and JavaScript

Criteria: Upon clicking a button from the selection of four buttons, all other buttons should become disabled except for the Next button. An alert window must appear when the Next button is clicked without selecting any other buttons, preventing navigatio ...

To calculate the sum of input field rows that are filled in upon button click using predetermined values (HTML, CSS, JavaScript)

Greetings for exploring this content. I have been creating a survey that involves rows of buttons which, when clicked, populate input fields with ratings ranging from 5 to -5. The current code fills in one of two input fields located on opposite sides of ...

Iterate over the HTML elements within a class and retrieve a specific property in JSON

Currently, I am in the process of developing a straightforward application that involves making an Ajax request to retrieve a Json object and then passing it to an HTML document. Essentially, this application functions as a vending machine where the produc ...

The error message states that `article.createdAt.toLocalDateString` is not a valid

const mongoose = require("mongoose"); const blogPostSchema = new mongoose.Schema({ title: String, image: String, description: String, createdAt: { type : Date, default : new Date() } }); const blogPos ...

The parent component can successfully call the setState function, but for some reason, the

In my code structure, I have the following setup (simplified): Here is the parent component: //code... const {handleClick} = useClick; <ul> {actions.map((action: string) => ( <li onClick={() => handleClick()} key={uuidv4()}> ...