Navigating Backend to Frontend naming conventions in Angular: A Guide

I am currently utilizing Angular on the front end and Postgresql as my database management system.

Displayed below are the names of columns in the database that are being accessed by the service:

export interface AmazonDataLog {  
    customer_id: number;
    first_target: string;
    last_target: string;
   
}

Below is the TypeScript file where the processIncomingRecord function will retrieve data and then render it on the user interface:

component.ts file

  firstLogs: AmazonDataLog | undefined = undefined;
 
  constructor(
    public userService: UserService,
    private records: AmmaService,
    private router: Router
  ){

    this.records.getNextRecord().subscribe(data => {
      this.processIncomingRecord(data);
    });

The following HTML code displays the retrieved data:

.html code

 <mat-divider></mat-divider>
 <mat-list-item class="bold">Amazon {{firstLogs.customer_id}} : {{firstLogs.first_target}}</mat-list-item>
 <mat-divider></mat-divider>
 <mat-divider></mat-divider>
 <mat-list-item class="bold">Alexa {{firstLogs.customer_id}} : {{firstLogs.last_target}}</mat-list-item>
 <mat-divider></mat-divider>
            

I am interested in renaming the backend variables to camel case and displaying them on the frontend:

Eg - The original backend service returns:

    customer_id: number;
    firstTarget: string;
    lastTarget: string;

For example, I would like to display them on the UI as follows:

   {{customerID}} {{firstTarget}} and {{lastTarget}} 

How can I make this change?

Answer №1

When it comes to renaming fields of an object that is already present, you have two main options to consider.

Option 1

Create three optional fields within your interface like this:

export interface AmazonDataLog {
    customer_id: number;
    first_target: string;
    last_target: string;
    customerID?: number;
    firstTarget?: string;
    lastTarget?: string;
}

Then, implement a method where you map the values accordingly:

mapToCamelCase(data: AmazonLogData): void {
    data.customerID = data.customer_id;
    data.firstTarget = data.first_target;
    data.lastTarget = data.last_target;
}

Since the object is processed "by reference," there's no need to return it.

Option 2

Alternatively, you can define a separate interface with CamelCase field names and perform the mapping:

export interface CcAmazonDataLog {
    customerID: number;
    firstTarget: string;
    lastTarget: string;
}

// After mapping, unnecessary fields can be removed if deemed necessary,
// although use caution as once removed they may not be accessible later on!
// (The delete-lines are commented out as a precaution)
mapToCamelCase(data: AmazonLogData): CcAmazonLogData  {
   // Instantiate an object ccdata using the interface CcAmazonLogData
   // [...]

    ccdata.customerID = data.customer_id;
    // delete data.customer_id;
    ccdata.firstTarget = data.first_target;
    // delete data.first_target;
    ccdata.lastTarget = data.last_target;
    // delete data.last_target;

    return ccdata;
}

Following the mapping process, you can then proceed as demonstrated below:

Inside the TypeScript file

this.records.getNextRecord().subscribe(data => {
    this.mapToCamelCase(data);
    this.processIncomingRecord(data);
});

Within the HTML

<mat-divider></mat-divider>
<mat-list-item class="bold">Amazon {{firstLogs?.customerID}} : {{firstLogs?.firstTarget}}</mat-list-item>
<mat-divider></mat-divider>
<mat-divider></mat-divider>
<mat-list-item class="bold">Alexa {{firstLogs?.customerID}} : {{firstLogs?.lastTarget}}</mat-list-item>
<mat-divider></mat-divider>

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

Why does `npm init react-app` automatically select yarn as the default package manager? (npm version 6.14.5)

After executing the command npm init react-app, I noticed that npm automatically selects yarn as the default package manager for the newly created app. To resolve this, I followed the steps provided in How Do I Uninstall Yarn to remove yarn from my system. ...

Dynamically set the value of a form in <mat-select> using binding

In my 'div' element, I have implemented a "mat-select" feature that contains a dropdown of country lists in a multi-select format. I am looking to automate the process of populating the countries within the "mat-select" when a button is clicked. ...

Which nodejs versions are compatible with async Iterators?

Which iterations of nodejs are compatible with async Iterators? Can it be adapted to function on previous versions of nodejs? usage for await (let content of promises) { // promises => array of promise objects console.log(content); } ...

Incorporating a conditional statement into the Array.from() method

Here is the code snippet that I am currently working with: AllDays= Array.from(moment.range(startDate, endDate).by('day')).map(day => day.format('YYYY-MM-DD')); I want to enhance this code by adding a conditional statement so that i ...

Angular 5 facing issue with loading external scripts dynamically

I have configured the external scripts in the .angular-cli.json file under the scripts property: ` "scripts": [ "../src/assets/plugins/jquery/jquery.min.js", "../src/assets/plugins/popper/popper.min.js", "../src/assets/plugins/jquer ...

Failure to load image logo when refreshing the page

There's something peculiar happening in my App.vue. Imagine I have a route link, let's say it's localhost/tools or any similar route. The logo image will display on this route. Take a look at the image here https://i.stack.imgur.com/6HaXI.p ...

Guide to creating a new browser tab in Java Script with customizable parameters

Here is a function I created to open a new window with a specific URL and pass certain parameters. function viewWeightAge() { var userNIC = document.getElementById("NICNo"); var childName = document.getElementById("c ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

Ways to change the chart type in ApexCharts

I'm seeking a way to change the chart type of an existing ApexCharts that has already been rendered. After reviewing the methods, I attempted to use the updateOptions() method, but encountered the error: Uncaught TypeError: Cannot read property &apos ...

Determine the mean of each group of n elements within a given array

I am looking for assistance with a coding challenge involving an array of numbers. The goal is to calculate the average of every 3 elements in the array and store these averages in a new array. Below is the code I currently have: var total = 0; //Array ...

Angular - Resending unsuccessful requests

We have successfully incorporated token authorization with refresh token logic into our application. While everything is functioning as expected, we are looking to enhance the retry mechanism for requests that fail due to token expiration. The entire proce ...

What is the best way to convert an array of objects into a string in nodejs?

[ RowDataPacket { House_Name: 'Merlin 5th Avenue', no_of_rooms: 6, Cost: 3400000, PropertyId: 2 }, RowDataPacket { House_Name: 'Presidential Building', no_of_rooms: 5, Cost: 3500000, PropertyId: 106 ...

intl-tel-input's getExtension function is returning a value of 'null'

I've been attempting to retrieve the extension of the mobile number that has been input. All other variables are functioning correctly, but the extension variable is returning a null value. It appears that it is sending a null value to the POST method ...

Challenges with utilizing Angular's asynchronous capabilities in managing local storage issues

Embarking on my journey with Angular, I have encountered challenges with async operations. My current struggle involves setting a private class value based on a key retrieved from localStorage before making an HTTP request. I am utilizing Ionic Native St ...

A comprehensive guide on leveraging redux's useSelector to access state data and execute a database fetch operation

Working on a project with redux, I am facing the challenge of creating a useSelector function that can determine if the values in the redux state are default. If not, it should trigger a database request to update the state. This task seems complex and I&a ...

The modal box appears to be malfunctioning

I am attempting to open the abc.html file (located in the same directory) in a modal box. Here is the code I am using, however, it doesn't seem to be working. Any assistance would be greatly appreciated. <!DOCTYPE html> <html> <head ...

I am unable to select the first item when using select2.js and setting a placeholder

I am experiencing an issue with my <select> list that is styled using select2.js. Everything seems to be functioning properly, except for when a placeholder is used. Users are unable to select the first item in the list initially. If they choose any ...

What techniques can be used to perform a complex JSON search in Javascript that involves multiple dimensions?

Currently, I'm in the process of developing a basic search system using JavaScript and JSON to fetch data stored within the JSON file. Within this file, multiple 'posts' are listed along with corresponding array of 'tags'. The prim ...

javascript callbacks used for language translation application

I am currently working on developing a translation engine with node.js. Coming from a Python/R background, I am having trouble grasping the concept of callbacks... The sentence for translation is: var sentence = "I want to translate this" Upon clicking ...

Encountering unspecified values when subscribing to a BehaviorSubject and receiving it as an Observable

My goal is to display the name of the currently logged-in user in the header of my application. However, I encountered an issue where upon refreshing the page, the value would be lost due to SPA behavior (even though the data is stored in local storage). T ...