Converting a "String" value to a specific "Type" in Angular 2 using TypeScript

This is my current object, Home points to the import statement for Home component.

import { Home } from '../home/home';


  arr = [
      { name: "Home", root: Home, icon: "calc" }
    ];

This is what I want to achieve:

 import { Home } from '../home/home';
 arr = [
          { name: "Home", root: Home, icon: "calc" }
        ];

I'm encountering an error because "Home" is being treated as a string. Using eval() resolves the issue but I am looking for an alternative solution.

Working code:

 for (var i = 0; i < arr.length; i++) { 
      arr[i].root = eval(arr[i].root);
    }

Answer №1

Based on your current situation:
You are dealing with a scenario where you receive JSON data from a server which includes names of classes that you will need to use during runtime.
These class names are represented as strings and your goal is to obtain the actual classes they represent.

While utilizing eval may be an option, it's important to note that using eval is generally discouraged, especially when dealing with external data sources. This caution is emphasized in resources such as this article from MDN:

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. Using eval() on a string that could be influenced by malicious parties can result in running harmful code on the user's device within the context of your webpage / extension. Additionally, third-party code can access the scope in which eval() was invoked, potentially leading to security vulnerabilities that Function does not have.

If you still opt for using eval, proceed with caution. Alternatively, you can maintain a registry of these classes:

const REGISTRY = {} as { [name: string]: { new(): any };

...
class Home { ... }
REGISTRY["Home"] = Home;

Then, you can do the following:

for (var i = 0; i < arr.length; i++) { 
    arr[i].root = REGISTRY[arr[i].root];
}

It's also worth mentioning that this approach introduces dependencies between the data received from the server and the client-side application.
Ensuring that the class names provided in your JSON align with the client-side implementations is crucial.
If you decide to rename a class on the client side, remember to make the corresponding update on the server side as well.
Ideally, it's better to focus on returning data exclusively and allow the client-side logic to determine how to handle and locate the necessary classes.

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

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

Utilize reactiveForms and the FileUpload component in Angular to effortlessly upload files

I'm currently utilizing primeng for my template and I've incorporated the p-fileupload component. However, I need to integrate it into a reactive form and I'm unsure where to place the formControlName since there is no visible input or label ...

Creating a multi-view routing system in Angular

I am currently in the process of creating a single page application with a user interface that resembles the following: One side displays a list of item images, and upon clicking on an item, the details such as a larger image will appear on the other side ...

What is the best way to declare only a portion of a JavaScript module?

I'm having trouble understanding declarations. If I only need to declare a portion of a module, is this the correct way to do it (disregarding the use of 'any')? import { Method as JaysonMethod } from 'jayson/promise'; declare cla ...

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

Efficiently sharing services in AngularJS across controllers without requiring multiple service calls

Currently, I am working on a project that involves the use of AngularJS. During the development of the module, I found myself needing to reuse data provided by a service in two separate controllers. I have a controller named Ctrl1 that interacts with an A ...

There is an implicit 'any' type error binding element 'currency' in Graphql React Typescript

I am facing an issue with my code. I want to use the EXCHANGE_RATES in renderedExchangeRates, but I am receiving an error message saying "Error Message: Binding element 'currency' implicitly has an 'any' type." I understand that this is ...

Need help with setting up a variable?

I'm having trouble figuring out how to store the value returned from a stored procedure in web API. How can I pass variables through AngularJS? I made a service call var promisePost = crudService.candidatePost(Candidates); promisePost.th ...

Is it necessary to use an EventEmitter explicitly when performing two-way binding in Angular 2?

If I have a Kitchen class structured like this: @Component({ template: ` <kitchen [(kitchenLunch)]=lunch></kitchen> ` }) export class House { private lunch: Lunch; } The House component: Includes a sub-component Ki ...

Utilizing an attribute's data within a custom Angular directive

Greetings from a new Angular enthusiast! I recently created a custom directive that is designed to display the value of an attribute in a span element: myApp.directive("myDirective", function(){ return { restrict : "E", template : "&l ...

Angular 5: Utilizing distinct router-outlets in separate modules for optimized lazy loading experience

Having two modules with routing module files and router-outlets in their html, I aim to load components based on the current module. The file tree structure is as follows: project |-- module2 |-- -- profil |-- -- - profil.component.html |-- -- - profil. ...

Angular Service failing to connect with API endpoint

I have been experimenting with a new service called vpnblocker, designed to identify whether a user is utilizing a VPN or not. I am closely following the specified documentation and referencing the API variables. Despite setting up my angular service to ma ...

When I utilize a component to create forms, the React component does not refresh itself

One of the components I am working with is a form handling component: import React, { useState } from "react"; export const useForm = (callback: any, initialState = {}) => { const [values, setValues] = useState(initialState); const onCha ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

Tips for getting Atom cucumber step jump package to function properly on a Windows operating system

Just recently, I installed the Atom text editor along with the cucumber-step package available at this link. However, after pressing CTRL+ALT+j, it failed to jump to the step implementation/definition. My operating system is Windows 10 and I am utilizing ...

Looking to update properties for elements within the Angular Material 16 mat-menu across the board?

Currently working with Angular Material 16 and I have a question regarding the height of buttons inside the mat-menu element. Here is an example of the code: <button mat-icon-button> <mat-icon>more_vert</mat-icon> </button> ...

Styling multiple checkbox items in an Angular Material Autocomplete

Is there a way to adjust the height of autocomplete multiple checkbox items in Angular Material? I'd like it to look like this With a line item height of 18px But instead, it looks like this when using multiple checkboxes With a different checkbox ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

HTTP requests are not working properly on my Ionic app after running the 'ionic build android' command

During the development process, I have been using ionic serve to test my app and everything has been working smoothly. Now, I am attempting to export the apk by running the command ionic build android, saving the 'android-debug.apk' file on my we ...