Exploring the power of global injectors in Angular 7 for component inheritance

Recently, I have been following a method outlined in a blog post on MSDN to simplify the extension of components without having to include all dependencies in the super() call. However, this approach seems to have ceased working in Angular 7 with Typescript 3.

The issue arises when I attempt to store the injector in a service after bootstrapping and then later retrieve it for use:

platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {
  // Save the module's injector in the AppInjector class
  console.log('Expected #1: saving app injector');
  AppInjector.setInjector(ref.injector);
})

Subsequently, in the base component, I try to access the stored injector:

export class BaseComponent {
  constructor() {
    console.log('Expected #2: retrieving saved injector');
    const injector = AppInjector.getInjector();
  }
}

However, upon reviewing the console logs, it appears that the order is mixed up – the BaseComponent's constructor is executed before the resolution of the boostrapModule() promise.

I am uncertain if there has been a change in how bootstrapping works in Angular 7 based on the console output. While this solution functioned correctly in Angular 6 with Typescript 2, it no longer does so with version 7. A broken app exemplifying this issue can be found on StackBlitz, following the principles mentioned in the MSDN article: https://stackblitz.com/edit/component-inheritance-angular-7

Therefore, the key question at hand is – how can we ensure that AppInjector.setInjector() occurs prior to AppInjector.getInjector()?

Answer №1

In the AppModule, I have configured the injector service by injecting Injector and setting it in the constructor of the module. This allows me to store the injector service in a global object.

export class AppModule {
  constructor(injector:Injector){
    // Storing module's injector in the AppInjector class
    console.log('Expected #1: storing app injector');
    AppInjector.setInjector(injector);
  }
}

Check out the demo here

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 is the correct way to configure the environment variables for the vscode plugin?

After attempting to set it using cross-env, the variable remained undefined following execution in VSCode. What steps can I take to resolve this issue? ...

Using TypeScript with React Bootstrap's <Col> component and setting the align attribute to 'center' can trigger a TS2322 warning

The React app I'm working on includes the code below. The Col component is imported from React-bootstrap <Col md={5} align="center"> This is a column </Col> When using Typescript, I received the following warning: ...

Navigating through elements in Angular

I am working with multiple Angular components housed within a display:flex div container. I am fetching datatable from an API, and it contains the same number of rows as there are components. Each row in the datatable corresponds to data for each compone ...

Utilizing Loops to Generate Unique CSS Designs on an HTML Page

View reference image ->Take a look at the reference image provided. ->In the image, a for loop is used to create box designs and displayed above. ->The goal is to change the background color and border color of all boxes using a single HTML cla ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

The property "state" of RouteComponentProps location does not exist in the provided type {}

We recently encountered a new error that was not present before. Previously, our code compiled without any issues and the compilation process went smoothly. However, individuals who installed the react application from scratch are now facing an error speci ...

Guide for launching Electron on a local host server during development and for production builds

I have a project using Next.js + Electron + Typescript. I used the npx create-next-app --example with-electron-typescript command to generate the initial code. When I run npm run dev (which actually runs npm run build-electron && electron . ), the ...

Determine the index of items within an array of objects in Lodash where a boolean property is set to true

I am new to using lodash after transitioning from C# where I occasionally used LINQ. I have discovered that lodash can be utilized for querying in a LINQ-style manner, but I'm struggling to retrieve the indexes of items in an array of objects with a b ...

Can you tell me how to add a custom CSS class to a cell in ag-grid using Angular?

I am facing a challenge with applying CSS to cells in ag-grid in Angular based on specific logic. I have assigned an object to the grid, where one of the fields contains a value for Object.hours and I need to apply styling based on the Object.status proper ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

When trying to console log a selected date, the output displays as undefined

<div class='col-sm-6'> <input [(ngModel)]="date" id="date" name="date" class="form-control" required/> </div> $(function () { $('#date').datetimepicker({ format: 'DD/MM/YYYY hh:mm' } ...

In the Vercel production environment, when building Next.js getStaticPaths with URL parameters, the slashes are represented as %

I've encountered an issue while implementing a nextjs dynamic route for my static documentation page. Everything works perfectly in my local environment, and the code compiles successfully. However, when I try to access the production URL, it doesn&ap ...

Is there a way to alter the date format for input elements within formGroups using Angular 7?

When the input is of type 'Date', the date format is dd/MM/yyyy. I need to convert the date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calendar). Below is the code snippet. <form [formGroup]="opportunityForm" (ngSubmit ...

There seems to be an issue with calling this particular expression. The elements within the type 'string | ((searchTerm: string) => Promise<void>) | []' are not all callable

Here is my unique useResults custom hook: import { useEffect, useState } from 'react'; import yelp from '../api/yelp'; export default () => { const [results, setResults] = useState([]); const [errorMessage, setErrorMessage] = us ...

Comprehending the concepts of Observables, Promises, using "this" keyword, and transferring data within Angular with TypeScript

I am trying to figure out why I keep receiving the error message: "Uncaught (in promise): TypeError: this.dealership is undefined" when working with the authentication.service.ts file. export class AuthenticationService { private currentUserSubject: ...

Establish a connection using Angular 4 HTTP POST to communicate with a Java REST API, as it is not permitted on the server

I am facing an issue with my Angular 4 client service that is calling a REST method declared on a Java server using a PostMapping annotation. When I make the call from Angular, it is not accepted by the server. However, when testing it on Postman, it work ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

Seasonal selection tool

I need a quarterly date picker feature, ideally using Angular. I am interested in something similar to the example shown below: https://i.stack.imgur.com/9i0Cl.png It appears that neither Bootstrap nor (Angular) Material have this capability. Are there a ...