The functionality of Angular/Typescript class.name appears to fail during a production build

Using Angular 5, I encountered an unusual problem with the class.name property. We have a TypeScript function as shown below:

export class ApiService
{
  public list<T>(c: new(values: Object)=> T)
  {
    var cname = c.name;
    ....
  }
}

When using this function in the development build of Angular (ng-build) with the Employee class like so:

export class Employee()
{
    public id:string;
    public name: string;

    constructor(values: Object = {}) {          
       Object.assign(this, values);          
    }
}

And somewhere in the code:

var list = api.list(Employee);

It works fine and 'cname' is equal to 'Employee' in the list function.

However, when we build the solution using ng build --env=prod, the code fails and 'cname' becomes undefined.

What could be causing this issue and how can it be resolved? Shouldn't something that functions correctly in the development build also work in production?

Answer №1

If you're encountering issues with minification, it may be due to the process that occurs during a production build. Minification is responsible for renaming your classes in order to reduce the size of the output file.

For more information on this topic, take a look at this question and answer: Angular-cli : How to ignore class names from being minified

As mentioned in the previous response, if you want to customize these options, you will have to use the command ng eject for your app. However, keep in mind that this action will limit some of the functionalities of the Angular CLI (such as ng build and ng serve).

For further insight into ng eject, refer to this GitHub comment here: https://github.com/angular/angular-cli/issues/6302#issuecomment-301220770

Answer №2

Encountered a similar issue with my production code where 'constructor.name' was coming back as an empty string. To tackle this, I implemented a solution by applying decorators to the classes that needed it. The decorator would then dynamically reassign the 'name' property at runtime, either with a specified class name or a generic one if no parameter was provided. See below for the decorator implementation:

import "reflect-metadata";
var __global__ClassName__id__ = 0;
export function ClassName(useThisName: string = null) {
    return function (target: any) {
       if (target.name.length === 0 || useThisName !== null) {
            Object.defineProperty(target, "name", {
                value: useThisName !== null ? useThisName : `__ClassName__${++__global__ClassName__id__}`,
                enumerable: false,
                writable: false,
                configurable: true
            });
        }
    }
}

This is how you can use the decorator in your code:

// Generate a dynamic class name
@Decorator.ClassName()
export class PopupMessage{ }

// Specify a custom class name
@Decorator.ClassName("PopupMessage")
export class PopupMessage{ }

// Utilize the class names as usual
var something = new Message.PopupMessage(1);
var samething = (<any>something).constructor.name == Message.PopupMessage.name;

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

Guide to setting a dynamic print style without affecting the screen media

In my report, there is a details section below. The screen provides instructions to view the details with a button that toggles the list's visibility. When printing the report, I only want the instructions to show if the list is visible. If the list ...

Troubleshooting: Angular Custom Elements malfunction on Firefox, Microsoft Edge, and Internet Explorer

Experimented with the Angular Elements Demo After downloading, installing, and building the demo locally. Implemented the following code: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Angular Eleme ...

Execute JavaScript code and showcase the result in the frame on the right side

On the left side of a frame, I have a menu. My goal is to invoke a javascript function that will load a new HTML page on the right side of the frame using XML data and an XSL template. When trying to achieve this with fixed parameters, the code works perf ...

Using regular expressions to eliminate text located outside of the tags within a string

Presented is a string consisting of an XML string below: var xmlString = "<str>rvrv</str>rvrv<q1>vrvv</q1>vrvrv<q2>rtvrvr</q2>"; I am seeking assistance on how to eliminate text that lies outside the tags (text no ...

Transform an array of Boolean values into a string array containing only the values that are true

Suppose we have an object like the following: likedFoods:{ pizza:true, pasta:false, steak:true, salad:false } We want to filter out the false values and convert it into a string array as shown below: compiledLikedFoods = ["pizza", "steak"] Is t ...

Navigating the issue of updateMany not functioning properly in mongoose and nodejs

I need assistance with updating the author name of a post whenever the user updates their profile name. My code is as follows: router('/:id', async (req, res) { if (req.body._id == req.params.id) { try { const user = await ...

Using a method call instead of a property for the ngFor directive can lead to an infinite loop of loading

Within my template, I have included the following code: <a *ngFor="let item of navItems" [routerLink]="item.link" routerLinkActive="active" class="navigation-item" [ngClass]="{'enabled': item.enabled}" > <span class="color ...

Using Three.js to transfer one object's rotation to another object

I have been attempting to transfer one object's rotation to another with no success using the following methods: //The first method rotates much faster than the original object's rotation boxme1.rotateOnAxis(new t.Vector3(0,1,0), cube.rotation.y ...

Refresh React Components on the Fly (Solr)

I am relatively new to ReactJS In my React class, I have a function that is rendering multiple items: (Sample) var app = app || {}; app.Results = React.createClass({ componentDidMount: function () { }, handleUpdateEvent: function(id) ...

The setInterval function continues to execute endlessly even after each interval is three months

I need to remove all expired OTP records every three months. In the file /sheduled-tasks/OTPRecords.js const prisma = require("../services/prisma"); const THREE_MONTHS = 1000 * 60 * 60 * 24 * 90; async function deleteExpiredOTPRecords() { ...

Display/Conceal JavaScript

I recently implemented a JavaScript function on my website to show/hide specific elements. However, being new to JavaScript, I have encountered some difficulties. I've spent quite some time troubleshooting the code but haven't been able to pinpoi ...

Focus loss occurs when the state changes in a Custom Tooltip containing an MUI TextField

Currently, I am utilizing MUI and have implemented a custom Tooltip for one specific TextField within my form. The issue arises when I start typing in this particular TextField as it loses focus immediately. Consequently, the state of the value in my formD ...

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...

"Discover the latest feature in the new Angular router: automatic scrolling functionality

The old ui-router and 1.4 angular router used to support autoscroll="true" to automatically scroll the page to the top when navigating to another route. Is there a way to achieve this with the latest new angular router? It seems like ng-outlet does not ha ...

The full height of the image cannot be captured by html2canvas

It baffles me that html2canvas is failing to capture the full height of the div. html2canvas($container, { height: $container.height(), onrendered: function(canvas) { var data = canvas.toDataURL('image/png'); ...

What is the best way to create transitions for item entry and exit in ReactJS without relying on external libraries?

I am looking to create an animation for a toast notification that appears when a user clicks on a button, all without the use of external libraries. The animation successfully triggers when the toast enters the screen upon clicking the button. However, I e ...

Utilizing Jquery Ajax to send a post request containing input values through Tampermonkey

I encountered an issue with my code - even though the logs in console show that it is working, I am unable to send the values to my server using AJAX post. jQ(document).on("keyup", "form input", function () { var value = jQ(this).val(); ...

Testing an ajax-driven website: what's the best approach?

Seeking to develop automated tests for my completely ajax-based website developed using Spring MVC/Java. I possess a basic understanding of Selenium and have managed to create some tests using this tool. The main issue lies in the fact that testing an aja ...

Encountering a 404 error while sending a session ID in a Post request using AngularJS

My services are hosted on a remote server, and I am consuming these services in a local AngularJS app. Everything works fine with REST requests that do not require a SessionID in the header. However, when I add the Session ID in the header, it does not wor ...

Guide for populating the chosen item in a combobox when the form control option has various parameters

I need help populating the selected saved item into the form control. <select class="form-control"> <option data-parameter-id="685" data-parent-id="1052" data-aggregation-id="null" data-aggregation-parameter="null">ABC</option> & ...