What is the best way to programmatically generate a service within Angular?

Is there a way to dynamically create services at runtime using a string name (like reflection)? For example:

let myService = new window[myClassName](myParams);

Alternatively, you could try:

let myService = Object.create(window[myClassName].prototype);
myService.constructor.apply(myService, myParams);

I have explored the Injector class, but it requires a type instead of a string (https://angular.io/api/core/Injector). Do you have any ideas on how to achieve this?

Answer №1

One way to utilize the Injector with strings is by specifying your providers as needed. For example, Angular's documentation shows how `[provide: Square]` can be shorthand for `

[provide: Square, useClass: Square]
(alternatively, you can use `useFactory` instead of `useClass` if you want to handle service instantiation yourself). You have the flexibility to change the first parameter (provide) to any Symbol or even a string of your choice.

To see this concept in action, check out the Proof of Concept I created on StackBlitz.

Answer №2

Give this a shot

object = new globalThis["myCustomClass"]();

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

Using socket.io-client in Angular 4: A Step-by-Step Guide

I am attempting to establish a connection between my server side, which is PHP Laravel with Echo WebSocket, and Angular 4. I have attempted to use both ng2-socket-io via npm and laravel-echo via npm, but unfortunately neither were successful. If anyone h ...

When attempting to pass an array of objects to a child component, TypeScript raises an error regarding types

Hey everyone, I'm currently facing an issue while trying to pass an array of objects as props. Here's the content of my data.json file: [ { "category": "Reaction", "score": 80, "icon": " ...

Leveraging the power of ReactJS and TypeScript within a Visual Studio environment for an MVC5 project

I am currently working on creating a basic example using ReactJS and TypeScript in Visual Studio 2015. Despite following several tutorials, none of them have met my specific requirements or worked as expected. My goal is to develop components as .tsx fil ...

imported classes from a module cannot be accessed within the same module

Here is some TypeScript code that I wrote: Within my module, I am importing a library called ts-events. import {SyncEvent} from 'ts-events' module MyModule{ export class MyService{ } } In the same module but in a different file, I'm ...

Angular attribute directive accesses a sibling attribute reference

Attempting to create an attribute directive named pagingContext that will work alongside the angular material sort directive matSort. The concept is to have an element structured like: <table matSort [pagingContext]="pagingContext"> With a directi ...

The optimal time to register for events within the Vue lifecycle

Currently, I am developing a Vue2 component using vue-component that includes a subcomponent. Here is an example: <note :bus="bus" :itemId="selectedId"></note> The subcomponent contains the following code snippet: <textarea v-model="text" ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

How can I programmatically trigger the optionSelected event in Angular Material's autocomplete?

I'm currently facing an issue with my Angular Autocomplete component. I am trying to trigger the (optionSelected) event within the ts file after a different event by setting the input with the updated option using this.myControl.setValue(options[1].va ...

What is the best way to connect internal files within Angular?

I am encountering an issue when trying to connect my login page from the navbar. Here is the code snippet for the navbar that I have: <div class="navbar-container"> <ul id="slide-out" class="side-nav center-align"> <li> <d ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

Developing a Universal Type in Typescript

Encountered an issue with generic types while working on a user-defined type(interface) structured like this: IList1: { prop1: string, prop2: number, prop3: string . . . } ILi ...

When utilizing a generic type with a class, type T fails to meet the specified constraint

export type ExtractType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] } export class CommandLineParse ...

Webpack and incorporating bespoke scripts

Can someone please help me understand how webpack works? I'm currently working on an Angular 2 project with a webpack starter and I have some JavaScript scripts from AWS (my SDK for API Gateway). These are about 10 JS files that I currently have liste ...

Learn the process of uploading files with the combination of Angular 2+, Express, and Node.js

Need help with uploading an image using Angular 4, Node, and Express with the Multer library. Check out my route.js file below: const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads') }, filename: fun ...

Uh oh! We encountered an error: Uncaught (in promise): Error: No routes found for the provided URL segment

There seems to be an issue with the router in my Angular application. I have successfully deployed it on an Apache server for production, and it is being served from the URL www.domain.com/clientng. Everything works fine, but I encounter an error in the br ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

Ways to retrieve the quantity of a particular value within an object using TypeScript

I'm inquiring about how to retrieve the number of a specific value within an object using TypeScript. Here is the structure of the object: obj : TestObject = { name: "test", street: "test" subobj1: { status: warning, time: ...

Multiple values are found in the 'Access-Control-Allow-Origin' header in Angular 7

After serving my Angular app on port 4202, I attempted to connect to a remote Spring MVC app using the code snippet below. this.http.post<Hero[]>('http://localhost:8080/api/hero/list', {"id":1}, httpOptions) However, I encountered the fol ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...