How to manually resolve a type by its string or name in Angular 2

I'm facing a challenge. Is it possible to resolve a component manually with just its name known?

Let's say I have a string variable that holds the name of a component, like "UserService".

I've been exploring Injector and came across methods like resolve() and resolveAndCreate() in the documentation (https://angular.io/docs/ts/latest/api/core/Injector-class.html)

However, the issue is I don't have the actual Type.

Any insights on this would be greatly appreciated.

Cheers,

Steve

UPDATE: Attempted the following:

System.import("path/to/service").then(p=>{

     var injector = Injector.resolveAndCreate([p[this.serviceName]]);//works

     var serviceInstance = injector.get(p[this.serviceName]); // Fails with "No provider for Http! (UserService -> Http)".


});

I do have Http available, as it has been provided during bootstrap and works well for other parts of the application.

bootstrap(AppComponent, [
    ROUTER_PROVIDERS, Http, HTTP_PROVIDERS, UrlBuilderService,
    provide(LocationStrategy, { useClass: HashLocationStrategy }),
    provide('notification', { useClass: NotificationService })
]);

Any thoughts?

Additional Update:

I adjusted the call to resolveAndCreate like this:

var injector = Injector.resolveAndCreate([p[this.serviceName], Http]);

but encountered an error:

No provider for ConnectionBackend! (UserService -> Http -> ConnectionBackend)

So, I modified it again:

var injector = Injector.resolveAndCreate([p[this.serviceName], Http, ConnectionBackend]);

this led to more missing components errors.

Eventually, I did this:

var injector = Injector.resolveAndCreate([p[this.serviceName], HTTP_PROVIDERS]);

and now everything is working as expected.

The confusion lies in why these components are not automatically resolved when they were provided during bootstrap.

Answer №1

fresh

If you need to access components by name, import them like this:

import * as components from './components'

Then, you can access them using this syntax:

var componentName = 'SomeComponent';
components[componentName]

For more information, check out this Plunker created by Rob Wormald on https://github.com/angular/angular/issues/7596#issuecomment-198199074

original

When using

Injector.resolveAndCreate(

You are creating a new injector that is separate from the Angular-created injector initialized with providers in bootstrap(..., [Providers]).
This custom injector can only resolve providers passed to resolveAndCreate().

If you want to utilize the same injector as your Angular application, you must inject the injector itself

constructor(private injector:Injector) {
  injector.get(...);
}

You have the option to create a child injector from the provided injector and override bindings if needed. The child injector will either use the overridden bindings or seek dependencies from parent injectors until reaching the root.

Answer №2

To achieve this functionality, you can utilize system.js (the loader utilized by angular2) in the following manner:

System.import('path/to/UserService').then(m => 
{
    //This allows access to the user service and its use in the injector, etc.
    Injector.resolveAndCreate([m.UserService]);
});

This method is thoroughly explained in the article: Implementing Lazy Loading of Route Components in Angular 2

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

Is there a way to extract information from an HttpClient Rest Api through interpolation?

I am currently facing an issue with a component in my project. The component is responsible for fetching data from a REST API using the HttpClient, and the data retrieval seems to be working fine as I can see the data being logged in the Console. However, ...

Reacting to Appwrite events in a React Native environment

My React Native application encounters an error when subscribing to realtime events. The error message reads as follows: ERROR Error: URLSearchParams.set is not implemented, js engine: hermes. appwriteClient .subscribe( `databases.${APPWRITE_DATAB ...

Incorporating Highcharts JS into a mobile app for a seamless data

After deciding to create an Android application that mirrors some features of a webpage, such as weather meteograms built with Highcharts, I delved into the process. Considering my use of Angular 2, I thought utilizing Angular 2 + NativeScript would be th ...

Exploring the power of Angular: Combining multiple observables seamlessly

I have a trio of services that return observables. The initial service retrieves a list of recipes, the second service fetches all ingredients for a specific recipe, and the final one acquires the quantity of a specific ingredient type. My goal is to call ...

Sending data to server using Angular's POST request

Even though I am attempting to transmit data to a server, it doesn't seem to be arriving. createUserProfile(email: string, password: string) { let userData = { email, password }; let authHeaders = new HttpHeaders({ 'Content-Type&a ...

Examining for a TypeError with Typescript and Jasmine

In my current project, I am faced with the challenge of writing unit tests in Typescript for an existing library that was originally written in plain JS. Most of our page logic is also written in plain JS. Some functions in this library throw exceptions if ...

The Angular router outlet is seamlessly activating without any manual intervention

Within the main view, a mat-button-toggle-group is used to toggle between a grid and list layout. The grid layout utilizes router-outlet to display the child component <router-outlet></router-outlet>, while the list layout directly implements t ...

How can we define and put into action a function in TypeScript that incorporates certain properties?

I have a vision of creating a message feature that can be invoked directly with overloading capabilities. I also wish to incorporate other function calls within this message feature, such as message.confirm(). Achieving this in TypeScript seems challenging ...

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

What is the process for downloading a .docx file encoded in Base64?

Trying to download a .docx file received from the backend. The object being received is shown below: Download attempt using the following code: const blob = new Blob([fileSource.FileData], { type: fileSource.FileType }); FileSaver.saveAs(blob, (fileSour ...

Testing the creation of elements dynamically with jestLooking into jest for dynamically adding

Attempting to test a dynamic element using TypeScript, but struggling to understand the process. Can anyone offer guidance? Below is the TypeScript file: export default class MyClass { constructor(){ this.render(); } render() { ...

What causes *ngIf to display blank boxes and what is the solution to resolve this problem?

I am currently working on an HTML project where I need to display objects from an array using Angular. My goal is to only show the objects in the array that are not empty. While I have managed to hide the content of empty objects, the boxes holding this co ...

How to render a markdown file from a specified path using React and TypeScript

I am currently working on setting up routes to different .md files within my react/typescript application. Inside my App.tsx file, I have the following code: <Router> <main> <nav className="navbar navbar-expand-md navbar-light bg ...

Ordering an array in Angular 2: A step-by-step guide

I am working on an Ionic 2 app with an older version of AngularJS that does not have the orderby pipe by default. As a result, I have an array structured like this: <div *ngFor="let boatBooking of boatBookings" style="padding: 0px; margin:0px;"> ...

Angular 7 routing glitches causing page refresh issues

Here is the issue I'm facing: I am looking for a way to switch between tabs in my navigation bar without having to refresh the entire website. I have just started working with Angular and I believe that the router should be able to route to a new pag ...

Selected Angular Radio Button

Back in the good ole days of basic HTML and CSS, I was able to achieve the following: input:checked+label { background-color: #f00; } <div class="col-xs-6"> <input type="radio" id="template-1" name="template" value="template1" checked> ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

What is the specific reference of the first parameter in NLS localize?

Regarding the question on localizing VSCode extensions, I am also curious why the localize function requires two parameters. When it comes to localizing settings, it's a simple process of replacing literal values with tokens surrounded by percent sig ...

incapable of altering the function of individual parts within ionic 3

I am currently working on creating a list of people for users to connect with. When a user clicks on the connect button, it should send a connection request to the chosen person. However, I am facing an issue where clicking on the connect button changes th ...