Encountering a Static Injector error in Angular 5 while trying to inject a component from a shared module

Here lies the code for my component file. My goal is to develop a reusable modal component using ng-bootstrap's modal feature. However, upon trying to import the following component from the shared module, I encounter a static injector error. Despite researching various resources, I am unable to pinpoint the issue with my implementation.

   import {Component} from '@angular/core';

    import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

    @Component({
      selector: 'ngbd-modal-basic',
      templateUrl: './customM.component.html'
    })
    export class CustomModalComponent {
      closeResult: string;

      constructor(private modalService: NgbModal) {}

      open(content) {
        this.modalService.open(content).result.then((result) => {
          this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
          this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        });
      }

      private getDismissReason(reason: any): string {
        if (reason === ModalDismissReasons.ESC) {
          return 'by pressing ESC';
        } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
          return 'by clicking on a backdrop';
        } else {
          return  `with: ${reason}`;
        }
      }
    }

Below is the SharedModule where the ModalComponent is declared and exported.

import { NgModule  } from '@angular/core';
import { CommonModule } from '@angular/common';

import { LoaderComponent } from './loader/loader.component';

import * as Shared from './index'; 

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    LoaderComponent,
    Shared.CustomModalComponent
  ],
  exports: [
    LoaderComponent,
    Shared.CustomModalComponent
  ],
  providers: []
})
export class SharedModule { 
  // static forRoot() : ModuleWithProviders {
  //   return {
  //     ngModule: SharedModule,
  //     providers: [ WebsocketService ]
  //   }
  // }
}

The static injector error arises at the declaration within the constructor of the following code snippet.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { finalize } from 'rxjs/operators';

import { environment } from '@env/environment';
import { Logger, I18nService, AuthenticationService } from '@app/core';

import { CustomModalComponent } from '../shared/_directives/custom-modal/customM.component';

const log = new Logger('Login');

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  version: string = environment.version;
  error: string;
  loginForm: FormGroup;
  isLoading = false;

  constructor(private router: Router,
              private formBuilder: FormBuilder,
              private i18nService: I18nService,
              private authenticationService: AuthenticationService,
              private c: CustomModalComponent) {
    this.createForm();
  }

Main App.module file

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule, NoopAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { TranslateModule } from '@ngx-translate/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxChartsModule } from '@swimlane/ngx-charts';
import { CoreModule } from '@app/core';
import { SharedModule } from '@app/shared';
import { HomeModule } from './home/home.module';
import { AboutModule } from './about/about.module';
import { LoginModule } from './login/login.module';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    NoopAnimationsModule,
    FormsModule,
    HttpModule,
    TranslateModule.forRoot(),
    NgbModule.forRoot(),
    CoreModule,
    SharedModule,
    HomeModule,
    AboutModule,
    LoginModule,
    NgxChartsModule,
    AppRoutingModule
  ],
  declarations: [AppComponent],
  providers: [ ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

Two key points to keep in mind:

In your app, there is a single root injector that houses all providers listed in the @NgModule.providers array of every module, including AppModule. Each component has its own injector (a child injector of the root injector) which contains providers listed in the @Component.providers array of that specific component. When Angular needs to resolve dependencies (like RightClickService) for a service (MainService), it searches for them in the root injector where all NgModule providers are stored.

If Angular needs to resolve dependencies (like RightClickService) for a component (RightClickComponent), it first looks in the component's injector. If not found, it then checks the parent component injector, continuing up the chain until reaching the root injector. If still not found, an error will be thrown.

I ran into the same issue myself and it was incredibly frustrating, but I managed to solve it by defining the dependency in the component module file.

Note: Adapted from 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

Trigger on the cancellation or completion of a nested observable

I'm seeking a way to detect if an inner observable was not successfully completed (due to everyone unsubscribing) and then emit a value in that scenario. Something akin to defaultIfEmpty, but the current solution isn't effective. A trigger exis ...

Tips for incorporating external AMD modules with Angular2 using WebPack

In my current project using Angular2, TypeScript, and WebPack, I am looking to incorporate the Esri ArcGIS JavaScript API. The API can be accessed from the following URL: By importing Map from 'esri/Map';, I aim to import the corresponding modul ...

Error: UserService (?) is missing parameters and cannot be resolved

Upon compiling my application, an error is appearing in the console: Uncaught Error: Can't resolve all parameters for UserService (?) Despite having @Injectable() present for the UserService, I am unsure where to troubleshoot further. import {Inj ...

Switching from a Promise to an Observable using React-Redux and TypeScript

I am struggling to grasp the concept of storing a Promise response into Redux. I believe finding a solution to this issue would greatly benefit me. Currently, I am utilizing a library that returns a Promise, and I wish to save this response - whether it i ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

Is it feasible to return data when utilizing the ModalController in Ionic 5, specifically when executing a swipeToClose or backdropDismiss action?

With the latest update to Ionic 5's ModalController, a new feature allows users to swipe down on a modal to close it in addition to using the backdropDismiss parameter. Here is an example of how to enable this functionality: const modal = await this. ...

What is the process of organizing information with http in Angular 2?

Currently, I am working through a heroes tutorial and have made progress with the code so far. You can view the code <a href="https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?preview" rel="nofollow noreferrer">here</a>. My next goal is to implement ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

Utilizing the split function within an ngIf statement in Angular

<div *ngIf="store[obj?.FundCode + obj?.PayWith].status == 'fail'">test</div> The method above is being utilized to combine two strings in order to map an array. It functions correctly, however, when attempting to incorporate the spli ...

Transferring information between pages within Next.js 13

I am currently working on a form that is meant to generate a Card using the information inputted into the form, which will then be displayed. While I have successfully implemented the printing feature, I am having difficulty transferring the form data to t ...

Can someone point me to the typescript build option in Visual Studio 2019 Community edition?

When I created a blank node.js web app on VS 2015, there was an option under project properties called "TYPESCRIPT BUILD" that allowed me to configure settings like combining JavaScript output into a single file. After upgrading to VS 2019 Community, I ca ...

Typescript - Iterating through CSV columns with precision

I am currently facing a challenge in TypeScript where I need to read a CSV file column by column. Here is an example of the CSV data: Prefix,Suffix Mr,Jr Mrs,Sr After researching on various Stack Overflow questions and reading through TypeScript document ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

Tips on customizing the Nuxt Route Middleware using Typescript

I am working on creating a route middleware in TypeScript that will validate the request.meta.auth field from the request object. I want to ensure this field has autocomplete options of 'user' and 'guest': export default defineNuxtRoute ...

Encountering a TS1005 error while trying to import types from a type definition file

Within my project, one of the libraries called parse5 is providing typing information in .d.ts files. The current syntax used to import types is causing several TypeScript errors during application runtime because TypeScript does not seem to recognize this ...

In TypeScript, encountering an unanticipated intersection

In my "models" registry, whenever I select a model and invoke a method on it, TypeScript anticipates an intersection of parameters across all registered models. To demonstrate this issue concisely, I've created a dummy method called "getName". expor ...

Steps for developing a versatile function Component

Can I create generic function components? I thought that the following example would work: type MyComponentProps<T> = T & { component: ComponentType<T>, primary?: boolean, size?: 'S' | 'M' | 'L' ...

Guide on importing SVG files dynamically from a web service and displaying them directly inline

With an extensive collection of SVG files on hand, my goal is to render them inline. Utilizing create-react-app, which comes equipped with @svgr/webpack, I am able to seamlessly add SVG inline as shown below: import { ReactComponent as SvgImage } from &apo ...

The process of invoking the AsyncThunk method within the Reducer method within the same Slice

Within my slice using reduxjs/toolkit, the state contains a ServiceRequest object as well as a ServiceRequest array. My objective is to dispatch a call to a reducer upon loading a component. This reducer will check if the ServiceRequest already exists in ...