Guide on dynamically injecting a helper class

Within my component, I am utilizing two different helper classes as shown below:

import {HelperA} ...
import {HelperB} ...
...

@Component({..})
export class MyComponent implements OnInit {
    helper: Helper;     
    constructor(private ref: ElementRef, private device: MyDeviceDetectionService) {}

    ngOnInit() {
        if (this.device.isMobile) {
            this.helper = new HelperA(this.ref);
        } else {
            this.helper = new HelperB(this.ref);
        }
    }
}

I am aware that this setup makes unit testing challenging. How can I handle the injection of these helpers in a way that only one is needed based on the isMobile condition being true or false?

Answer №1

You have the ability to pass all that information on to the injector. If the two assistants share a superclass called Helper, you can utilize the useFactory provider option to instantiate the necessary helper:

providers: [
  ...,
  { provide: Helper, useFactory: createAssistant, deps: [MyToolDetectionService, ElementRef] },
]

The factory function would be as follows:

export function createAssistant(tool: MyToolDetectionService, reference: ElementRef): Helper {
  if (tool.isPortable) {
    return new AssistantA(reference);
  } else {
    return new AssistantB(reference);
  }
}

It is important to note that this code should reside in the component's providers array since the element reference is not accessible at the module level.

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

What does 'this' refer to in a JavaScript function that is inside an object?

I'm currently working with a JavaScript code snippet that looks like the example below. On this particular line, this.orgBusinessKey = this.user.noaOrganisationList[0].businessKey; I'm wondering if the this scope will contain the user instance ...

What should I do about typescript and ES6?

An error occurred while running my code: [0] app/components/people/details/PersonDetailComponent.ts(27,35): error TS2339: Property 'person' is missing from type '{}'. Here is the code snippet in question: export class PersonDeta ...

Is the state variable not being properly set by using React's setState within the useCallback() hook?

Within a React FunctionComponent, I have code that follows this pattern: const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray, someFunction }) => { const [someStateObjVar, setSomeStateObjVar] = React.useState({}); const [ ...

Unexpected Secondary Map Selector Appears When Leaflet Overlay is Added

Working on enhancing an existing leaflet map by adding overlays has presented some challenges. Initially, adding different map types resulted in the leaflet selector appearing at the top right corner. However, when attempting to add LayerGroups as overlays ...

React problem with manipulating JSON arrays

In my React application, I am working with an array that looks like this: [ { year: 2014, field: "Coal", value: 100 }, { year: 2014, field: "power", value: 200 }, { year: 2014, field: "oil", value: 20 }, { ...

A TypeScript object with user-defined keys

I have a question about utilizing TypeScript records with a custom Type as keys. Essentially, I have a specific type (a limited set of strings) that I want to use as keys for my record. My goal is to start with an empty initialization of this record. type ...

Jest ran into a surprising token related to NUXT typescript

After spending two days searching and trying various solutions without success, I am reaching out for help. Can anyone provide a clue? Below are the configuration files I am using. Any assistance would be greatly appreciated. jest.config.js .babelrc .babe ...

Publish an Angular application's production version using Zeit Now

I've been utilizing zeit now for deploying an Angular application. The steps I followed can be found in this guide. The Angular app was created using the Angular CLI and was developed locally using the command ng serve. Deployment was done by executi ...

"Attempting to access a Service in Angular before it has been initialized is

When I try to run tests, they fail right at the beginning with an error message: Chrome 83.0.4103.61 (Linux x86_64) ERROR An error was thrown in afterAll Uncaught ReferenceError: Cannot access 'SomeService' before initialization ReferenceE ...

Using TypeScript to define generic types for classes, method parameters, and method return types

I am facing an issue with this particular function function getCollection<T>(collectionType: T): Collection<T> { return new Collection<T>() } In the Collection class, I have the following code snippet export class Collection<T> { ...

State management in React using hooks

Recently, I've been grappling with form validation while working on a signup form for my React app using Next.js. I've noticed that many sign up pages typically hide an "invalid" message until the user interacts with an input field. I attempted t ...

Discover the return types in Typescript by inferring from a collection of functions within an

Imagine you have an object { num1: 1, num2: 2, str: "abc" } Your goal is to develop a function that accepts any similar object as the first parameter, and a custom selectors object as the second parameter. function fn<O extends object, ...

Difficulty Encountered While Deploying Mean Stack Application on Heroku

I am embarking on my first journey of building a MEAN stack application, and I successfully created it locally. However, when attempting to host it on Heroku, things didn't go as planned. After researching online, I learned that both Angular and Expre ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

What sets apart an index signature from a Record when dealing with an empty object?

I'm struggling to differentiate between index signatures and record types. Can someone clarify the distinctions and suggest when each should be used? In particular, I want to specify the type of an object with random strings for keys and values that ...

"Unlocking the Power of Monaco Editor: A Guide to Fetching CompletionItems from Your

Currently, I have integrated the fantastic monaco editor into my Angular 8 app for editing formulas. Everything is working fine, but now I need the list of suggestions (CompletionItems) to update dynamically. I have utilized the ngx-monaco-editor module a ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

Unexpected behavior encountered when running Angular 8 radio button checked function

I have an Angular 8 web app with some unique logic implemented as shown below: HTML: <div *ngFor="let item of selectedItems;"> <input type="radio" [(ngModel)]="mySelectedItem" [value]="item.key" (ngModelChange)="setCh ...

In my Angular project, I'm currently working on retrieving a boolean value from a service. However, I'm encountering an issue where the

I'm currently working on a basic functionality that determines whether I am a part of a team or not, providing a simple true or false response. The backend validation has been successfully completed; however, the issue lies within my angular applicati ...

Transforming Angular 4's folder structure for improved architecture simplicity

I am faced with the challenge of organizing files and folders within an Angular 4 project in a way that allows for easy reorganization. Currently, my approach looks like this: ├───core │ │ core.module.ts │ │ index.ts │ │ │ ...