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

"Trouble with Bootstrap Collapse function - Utilizing ng-bootstrap, eliminating the need for JQuery

In my Angular 8 project, I have Bootstrap 4.3.1 and ng-bootstrap 5.1.1 integrated. As per the ng-bootstrap documentation, including ng-bootstrap in your project eliminates the need to manually add jQuery, as it is encapsulated by ng-bootstrap and not requ ...

Display the inputs from a reactive form in a different component

I am currently facing a situation where I have multiple components, such as component A, containing a reactive form. The data from these forms is stored in a central service. My goal now is to display a preview of this form in component B. However, upon na ...

What could be causing Angular to replace the original variable?

As a newcomer to Angular, I've been working on this code for hours now. Hopefully, it will all come together for someone out there who can make sense of it. export class QuizComponent implements OnInit { originalArray: IArray[] = []; tempArray: I ...

How can I ensure that all the text is always in lowercase in my Angular project?

Is there a way to ensure that when a user enters text into an input field to search for a chip, the text is always converted to lowercase before being processed? Currently, it seems possible for a user to create multiple chips with variations in capitaliza ...

Arranging an array of integers followed by sorting by the decimal part of each value in a particular sequence using JavaScript

Below is an example of sorting an array: let arr = ['100.12', '100.8', '100.11', '100.9']; When sorted traditionally, the output is: '100.11', '100.12', '100.8', '100.9' Ho ...

Grid display not showing scheduled events

I am encountering an issue with fullcalendar in my project where it is not showing the events within the day grid. Despite attempting to adjust the timezone and experimenting with different combinations of times and dates, the problem persists. // Html ...

What methods can be used to avoid getting distracted by input?

Is there a way to prevent the input field in angular-material2 from gaining focus when clicking on a visibility button? To see an example of how it works, visit: material.angular.io Image before pressing the button: https://i.stack.imgur.com/5SmKv.png ...

Ways to generate an Angular 7 component

Seeking guidance on creating an angular 7 component. I have forked a jsFiddle at this link: https://jsfiddle.net/gauravshrestha/fdxsywLv/. The chart in the fiddle allows data points to be dragged up and down. My goal is to convert this into a component whe ...

Tips for resolving relative child routes in Angular

Routing Configuration const routes: Routes = [ { path: '', loadChildren: './home/home.module#HomeModule' }, { path: 'admin', loadChildren: './admin/admin.module#AdminModule' } ]; Nested Home Routing const ro ...

Obtain data from the DOM using ng-select in Angular 10

In my Angular 10 project, I have certain views where I utilize ng-select to showcase and obtain data. The QA team has tests in place that depend on element id and DOM value, specifically designed for basic select elements. With a simple select, we are able ...

Guide to integrating location-based QR code verification

Currently, I am developing an Angular application where I am utilizing an npm package to generate QR codes. One of my main requirements is to incorporate location-based functionality into the QR code system. For instance, if a user is at a specific hotel a ...

Determining the Best Option: React JS vs Angular UI Framework

After researching the latest versions of React and Angular online, I discovered that both are suitable for developing Web Application UI. However, I also realized that there are key differences to consider when choosing between the two. Let's say I h ...

Angular and Bootstrap project with an advanced dropdown menu featuring multiple levels

Looking to create a multi-level drop-down menu using TypeScript without relying on jQuery? Bootstrap CSS framework may not have exactly what you need. Wondering how to implement a multi-level dropdown in your Angular project using HTML, CSS, and TypeScrip ...

Creating templates for both classes and individual objects is an essential part of object-oriented programming

I am working on a simple game project using TypeScript. My goal is to utilize interfaces to implement them in classes and pass them as arguments for creating new instances of a class. interface ObjectConstructor { element: HTMLElement; x_pos: numbe ...

What is the correct way to set up Typescript with external packages for Internet Explorer 11 using Babel 7 and Webpack 4?

After releasing a new version of our react app, we encountered an issue with IE11 complaining about the use of the let keyword. Upon investigation, we discovered that upgrading the query-string package from version 5.1.0 to 6.4.0 introduced the usage of th ...

Turn off the button and add a CSS class to it when sending a message

I have an Angular 7 component with a form that includes the following TypeScript code: export class MessageComponent implements OnInit { message: FormGroup; constructor(private formBuilder: FormBuilder, private messageService: MessageService) { } ...

What is the correct way to close an ngx-contextmenu in an Angular application?

In my angular project, I implemented an ngx-contextmenu. Within one of my components, the template includes the following code: <div... [contextMenu]="basicMenu"> <context-menu>..... </div> After some time, the component with the conte ...

Display a free Admob banner within an Ionic 3 application

I have integrated Admob's banner into my Ionic 3 app following the guidelines provided in the Ionic documentation at this link. Below is the code snippet I used for displaying the banner on the homepage: import { Component } from '@angular/core ...

Tips on sorting a nested array in a React TypeScript project

Hey there! I currently have a working filter in React that utilizes a List (I am using Mantine.dev as my CSS template): <List> {locations.filter(location => { const locServices: Service[] = []; location.services.forEach(service => { ...

Linking typescript error messages with their respective compiler configurations (tsconfig.json)

Is there a way to identify which compiler option corresponds to a specific Typescript error? While working with Typescript in VSCode, I often encounter errors like initializer provides no value for this binding element. (Please note that these are warnin ...