Tips for binding a type that has been imported dynamically

Struggling to automatically link templates to an inversifyjs container, but all attempts have failed. Seeking assistance!

private templates = [
    {file: './component.html.tpl', obj: 'HtmlTemplate'},
    {file: './component.tpl.ts', obj: 'ComponentTemplate'}
];
private container = new Container();
bind(){
    // original and working code 
    // this.container.bind<ITemplate>('HtmlTemplate').to(HtmlTemplate);
    // this.container.bind<ITemplate>('ComponentTemplate').to(ComponentTemplate);
    this.templates.forEach(template => {
        import(template.file).then(mod => {
            console.log(mod.default, template);
            // is this correct (seems to work) => 
            this.container.bind<ITemplate>(template.obj).to(mod.default);
            console.log('bound =>', mod.default);
        });
    });
}

and files ./component.html.tpl

@injectable() export default class HtmlTemplate implements ITemplate { ... }

and ./component.ts.tpl

@injectable() export default class ComponentTemplate implements ITemplate { ... }

Displayed as expected in the console:

[Function: HtmlTemplate] { file: './component.html.tpl', obj: 'HtmlTemplate' }
[Function: ComponentTemplate] { file: './component.tpl.ts', obj: 'ComponentTemplate' }

However, expected the following code snippet within the foreach statement:

this.container.bind<ITemplate>(template.obj).to(mod.default);

to be similar to this:

this.container.bind<HtmlTemplate>('HtmlTemplate').to(HtmlTemplate);
this.container.bind<ComponentTemplate>('ComponentTemplate').to(ComponentTemplate);

When trying to access it in another loop:

this.templates.forEach(template => {
    const tpl = this.container.get<ITemplate>(template.obj);
...

An error is thrown:

Error: No matching bindings found for serviceIdentifier HtmlTemplate

Any solutions to this problem?

Answer №1

The current code implementation is facing issues related to control flow. There are promises in the code that are not properly chained, leading to inefficient error handling and potential race conditions.

It is recommended to chain every promise for better control flow. Additionally, the use of forEach in ES6 is discouraged due to its complexities when working with promises, generators, and async functions. The code can be optimized by refactoring it to utilize more async functions:

async bind(){
    for (const template of this.templates)
       const mod = await import(template.file);
       this.container.bind<ITemplate>(template.obj).to(mod.default);
    }
}

The code segment using bind should also be properly chained to avoid constructing promises incorrectly:

async bind() {
    // binding for when the widget is needed;
    for (const component of this.components)
        component.widget = this.container.get<Widget>(component.name);
        if(component.widget) {
            await component.widget.configure();
            await component.widget.bind();
        } else {
            console.error(`widget ${component.name} not resolved`);
        }
    });

    return this;
}

An alternative approach is to eliminate asynchronous initialization routines where possible, as they are primarily required for dynamic import(). Instead, consider replacing import() promises with synchronous require statements, as import() falls back to require in Node.js software environment.

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

Generating a font file using webpack in the monaco-editor package

We are currently in the process of integrating a new package into our project that has a dependency on the monaco-editor module. Let me provide you with some details about our project: We have ejected from the create-react-app project Our project is writ ...

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

Service call delay not displayed on screen

I have a function that I execute in my component's ngOnInit lifecycle hook. This function calls a service to fetch data and populate an array. Once that array is filled, I then call another service method using the data from the first array to populat ...

How to retrieve Angular directive name using TypeScript

I have successfully implemented the following AngularJS directive: export module Directives { export class PasswordsMatch implements ng.IDirective { public static Factory(name: string) : ng.IDirectiveFactory { return () => new ...

Signal a refusal when the body structure does not meet the anticipated criteria

As I develop a node server using express, my goal is to ensure that the types received in the body are enforced. An example of what I am aiming for is: interface User { uid: string, email?: string, active: boolean, } app.put('/user', (req ...

Error encountered with TypeScript when utilizing conditional types in React components

Having trouble with TypeScript error when working with conditional types in React components. The issue arises when attempting to render different component types based on a type prop and providing corresponding props for each type. type PairingCardProps ...

The Vue component's TypeScript object prop type does not match the expected value

Having trouble with the type of Object properties in Vue Single File Components using TypeScript (created with Vue CLI 3)? Check out the example below to see the issue. The type of this.product is currently showing as (() => any) | ComputedOptions<a ...

What is the best way to define the type of an object in TypeScript when passing it to a function

I am currently working on a function that accepts an object of keys with values that have specific types. The type for one field is determined by the type of another field in the same object. Here is the code: // Consider this Alpha type and echo function. ...

Exploring the world of shaders through the lens of Typescript and React three fiber

Looking to implement shaders in React-three-fiber using Typescript. Shader file: import { ShaderMaterial } from "three" import { extend } from "react-three-fiber" class CustomMaterial extends ShaderMaterial { constructor() { supe ...

Maximizing the functionality of rowDoubleClick in Angular for consistent use across various components with shared ag-grid instances

I have implemented an ag-grid in 4 different Angular Components. My goal is to only enable the rowDoubleClicked functionality for one specific component. Unfortunately, when I apply this feature to the grid, it becomes enabled for all components. How can ...

Issue with prop type: MUI - experiencing a warning while using ReactJS with MUI?

Upon attempting to open the datepicker by clicking on the icon, I encounter the following warning. Here is the code snippet where the error occurs: const DatePickerTextField = React.forwardRef((props: TextFieldProps, ref) => { const theme = useTheme() ...

Cannot be assigned to type "never" after applying a type predicate

I'm attempting to merge a method for creating strongly typed strings with type predicates but encountering issues, as evidenced by the following code snippet: https://i.sstatic.net/2b9pO.png The issue I'm facing is TS2339: Property 'substr& ...

Using Generic Types in Response DTO with Typescript, NestJs, and Class Transformer

In my project, I am dealing with multiple endpoints that provide responses along with pagination details. My goal is to have a single parent type for the pagination and be able to use different data types for the data parameter. I attempted the following ...

Is it necessary for a TypeScript Library's repository to include the JavaScript version?

Is it necessary to include a JavaScript version of the library along with the Typescript repository for consumers? Or is it best to let consumers handle the compilation process themselves? Or should I consider another approach altogether? ...

"Utilize Tuple in TypeScript to achieve high performance programming

I've been delving into TypeScript, focusing on the tuple type. As per information from the documentation, here is the definition of a tuple: A tuple type is another form of Array type that precisely knows its element count and types at specific posi ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

The presence of an Angular pipe is causing interference with the execution of a template

I've developed an application that can organize an array of objects in either ascending or descending order based on a specific property value using the custom function sortByField(). Additionally, the app allows users to filter data by entering a sea ...

Framer Motion's AnimatePresence feature fails to trigger animations when switching between pages

I'm running into issues with the Framer Motion library, specifically with the AnimatePresence transition. I've managed to make it work in normal situations, but when I encapsulate my Routes within a custom implementation, the exit animation fails ...

Guide to sending a collection of templates to an Angular component

As a beginner in Angular, I've been working on creating a carousel component that can be shared. The structure of this component is based on the latest version of Bootstrap and I am looking to allow templates to be injected by the caller. For instanc ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...