Error: No injection provider found for function(){}!

After countless hours of setting up a custom AOT in Angular 7 project without CLI and debugging, I have encountered the following error:

Uncaught Error: StaticInjectorError(Platform: core)[function(){}]: 
  NullInjectorError: No provider for function(){}!
    at t.get (injector.ts:43)
    at injector.ts:346
    at Xa (injector.ts:288)
    at t.get (injector.ts:168)
    at Cp (application_ref.ts:41)
    at t.bootstrapModule (application_ref.ts:262)
    at Object.<anonymous> (main-aot.ts:14)
    at n (bootstrap:19)
    at bootstrap:83
    at bootstrap:83

Here is my app module definition:

import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { InlineSVGModule } from 'ng-inline-svg';
import { APP_BASE_HREF } from '@angular/common';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { FeatureRoutingModule } from './app-routing.module';
/**
 * Core
 */
import { HeaderComponent } from './core/header/header.component';
import { AppSettingsComponent } from './core/header/app-settings/app-settings.component';
import { SidebarComponent } from './core/sidebar/sidebar.component';
import { PreloaderComponent } from './core/preloader/preloader.component';
import { TranslationLoader } from './services/translation.service';
/**
 * Shared
 */
import { PopupsDirective } from './shared/popups/popups.directive';
/**
 * Component
 */
import { StructureComponent } from './component/structure/structure.component';
import { OverviewComponent } from './component/overview/overview.component';
import { MainContentComponent } from './component/main-content/main-content.component';
import { NavigationStripeComponent } from './component/main-content/navigation-stripe/navigation-stripe.component';
import { TestDirective } from './component/tooltip/serviceCalls.directive';
import { TooltipService } from './component/tooltip/tooltip.service';
import { TooltipComponent } from './component/tooltip/tooltip.component';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslationLoader(http);
}

@NgModule({
  // rendering in browser environment
  imports: [
    BrowserModule,
    FeatureRoutingModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (HttpLoaderFactory),
        deps: [HttpClient]
      }
    }),
    InlineSVGModule.forRoot(),
    HttpClientModule
  ],
  // register services at root level
  providers: [
    TooltipService,
    { provide: APP_BASE_HREF, useValue: `${window['_app_base']}/` || '/' }
  ],
  // components declarations
  declarations: [
    AppComponent,
    HeaderComponent,
    AppSettingsComponent,
    SidebarComponent,
    PreloaderComponent,
    StructureComponent,
    OverviewComponent,
    MainContentComponent,
    TestDirective,
    TooltipComponent,
    PreloaderComponent,
    PopupsDirective,
    NavigationStripeComponent
  ],
  // bootstrap component
  bootstrap: [AppComponent]
})
export class AppModule {
}

This is the component:

import { Component, OnInit } from '@angular/core';
import { AppService } from './services/app.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'kpi-main',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  theme: string;
  sidebarPref: object = {};
  stickyHeader: string = '';
  user: object = {};

  constructor (private appService: AppService, private translate: TranslateService) {
    translate.setDefaultLang('en');
    translate.use('en');
  }

  ngOnInit(): void {
    this.appService.getLayoutPreferences().subscribe(layout => {
      this.theme = layout.theme.value;
      this.sidebarPref = layout.sidebar_small;
      this.stickyHeader = layout.stickyHeader.visible;
      this.user = layout.sidebar_small.user;
    });
  }
}

This is my service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Response } from '@angular/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  theme: string = '';

  constructor (private http: HttpClient) { }

  setSidebarPref(obj: object): Observable<any> {
    return this.http.put('../api/v1.0/users/me/preferences', { 'batch' : obj }, { withCredentials: true } );
  }

  getUserImage(): Observable<any> {
    return this.http.get('../api/v1.0/users/me/image', { responseType: 'blob', withCredentials: true });
  }

  getLayoutPreferences(): Observable<any> {
    return this.http.get('../api/v1.0/properties/layout', { withCredentials: true });
  }

  handleError(error: Response) {
    console.log(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}

I am facing a NullInjector error in my app after setting up AOT in Angular. Any insights on how to resolve this would be greatly appreciated.

Update Upon further investigation, I have identified the issue in my main-aot.ts file and the way ngfactory is created. Here is the file:

import 'core-js/es7/reflect';
import 'zone.js/dist/zone';

import { platformBrowser } from '@angular/platform-browser';
import { AppModule } from './app/app.module';

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

enableProdMode();

platformBrowser().bootstrapModule(<any>AppModule)
  .catch(err => console.error(err));

Answer №1

When setting up your TranslateModule import, make sure to use a class instead of a function in the parentheses for loader.useFactory:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    // useFactory: (HttpLoaderFactory), <- Here
    useFactory: HttpLoaderFactory,
    deps: [HttpClient]
  }
}),
// ...

Answer №2

If anyone else is encountering a similar issue, I was able to find a solution here. Even though the initial problem reported was not identical to mine, the response from ckapilla resolved my issue.

@ngtools\webpack AOT doesn't work OR freezes at 95% emitting

Answer №3

To implement @Injectable in your code, simply add:

@Injectable({ providedIn: 'root' }) export class ErrorHandler {}

Answer №4

Encountered a similar issue, but I was able to resolve it by removing extra injectors from the tsconfig.json file.

It turns out I had added some extra things in the file, such as: "disableTypeScriptVersionCheck": true

For example

{
"angularCompilerOptions": {
"disableTypeScriptVersionCheck": true
},
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"skipLibCheck": true,
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
}
}

After making these changes:

{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"skipLibCheck": true,
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
}
}

Hopefully, this solution will be helpful to others facing a similar issue.

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

Any alterations made to an object in one component result in changes being reflected across all components

I currently have the following item.ts file: item.ts export interface IItem { name: string; isActive?: boolean; } const data: IItem[] = [ { name: 'item1', isActive: true }, { name: 'item2', isActive: true } ...

The functionality of the Protractor right click feature is smooth, however, there seems to be an issue with selecting

https://i.sstatic.net/KoGto.png Even though I can locate the button within the context menu, I am facing difficulty in clicking it. The code mentioned below is successfully able to click the button, but an error message pops up indicating: Failed: script ...

Breaking down CSV rows and transforming numerical data (Typescript, Javascript)

Looking to convert a row from a csv file into an array and then transform the numeric values from string format. This represents my csv file row: const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323"; My objective is to create this array (with the ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

Tips for preventing "timeout while waiting for third-party check iframe message" when using Keycloak and Angular

I'm in the process of securing an Angular application with a Keycloak server. I've followed several tutorials with similar instructions, but I encountered an issue that has me stuck: Timeout when waiting for 3rd party check iframe message. My ...

Height and placeholder issue with ion-searchbar

Hey there, I hope everything is going well for you. I've encountered a problem with the Ionic 5 - Angular Searchbar feature. This is how I added the searchbar: <ion-searchbar [(ngModel)]="text" (ionChange)="sear ...

What is the proper way to incorporate the "pdf" package into a TypeScript project?

I recently installed pdf and its types using the following command: npm install --save pdf @types/pdf However, I am struggling to find any documentation on how to actually use this package. When I try the following code: import {PDFJS} from 'pdf&ap ...

Alter the class based on the incoming string from the rxjs stream

I have a stream that outputs strings, and based on these strings I want to apply certain classes to a specific tag: If the string is "ok", add class "fa-check" If the string is "loading", add classes "fa-spin" and "fa-spinner" If the string is "error", a ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

Creating a custom provider for enum objects: a step-by-step guide!

While working with Google Guice 4.1.0 for creating the provider, I encountered an issue when trying to inject an object of enum. The error message received was "Error in custom provider, java.lang.IllegalArgumentException: Cannot reflectively create enum o ...

Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files. The variables I need are stored in src/styles/_variables.scss Here is my tsconfig.json: { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": ".", "allowJs": tr ...

Having trouble importing AnimeJS into an Ionic-Angular project

I successfully added AnimeJS to my Ionic 4 project using the commands below: npm i animejs --save npm i @types/animejs --save To reference AnimeJS, I used the following import statement: import * as anime from 'animejs' However, whenever I tr ...

The best location for storing Typescript files within an ASP.NET Core project

My Typescript app is built on AngularJS 2 with ASP.NET Core, and currently I store my TS files in the wwwroot directory. While this setup works well during development, I am concerned about how it will function in production. I aim to deploy only minified ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

Ways to limit file access and downloads on an IIS server

After deploying our Angular app (dist folder) on an IIS server, everything seems to be working well. However, there is a concerning issue where anyone can access and download the font files directly from the server without needing to log in. For example, o ...

How can I implement a method to configure a 404 HTTP header in Angular 5 when a route is not found?

Is it possible to display a custom 404 header on the current page when there is no route matching my array? If not, could this potentially create SEO issues and have unknown pages indexed by search engines? ...

Numerous Angular projects nestled neatly within one single overarching project

As my angular project continues to grow, the number of files is increasing and the overall size of the project is expanding I am considering breaking the project into multiple parts. I am thinking of implementing a microservice architecture For instance ...

Exploring Angular 5: Managing HTTP Headers and Utilizing URL Parameters

I am currently working on an Angular project that involves third-party authentication, which redirects to our app with additional information in the HTTP headers. Here are the questions I have: What is the best way to extract the information from the HT ...

Issue with the jasmine node package within an Angular 2 environment

I encountered the following error message: After attempting to switch my typescript version, the problem persisted. Even after running npm update --save, I was unable to resolve the issue. Error in [default] /Users/gdayton/Documents/auction/node_modules ...