Encountered in the Angular library: NG0203 error stating that inject() should only be invoked within an injection context like a constructor, factory function, or field initializer

Having recently updated my Angular project from version 9 to 15, I encountered the following issue. Any assistance would be greatly appreciated as I have been struggling with it for over 2 weeks.

The problem lies within app-lib.module.ts in the Angular library.

import { HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpService,
      multi: true
    }, ],

Another problematic file is hero.service.ts in my Angular library.

import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HeroService {
  texting: string = 'Wow!';
  constructor(private http: HttpClient) { }

  getResult() {
    return 'Wow!!!!!!';
  }
}

The error occurs when including (private http: HttpClient) in the constructor as shown above. Removing it allows the app to function properly.

Error: Uncaught (in promise): Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. Find more at https://angular.io/errors/NG0203
Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`.

Following the update from Angular 9 to 15 in one of my projects, this issue arose and any guidance on resolving it would be highly appreciated. I've been grappling with it for quite some time now.

Answer №1

Dealing with a similar obstacle arose as I attempted to upgrade my software from 9.1 to 15.2.9. The resolution came when I adjusted the version to 15.1.3. It's important to inspect your package-lock.json file for any conflicts within the angular versions. In my scenario, a library I was using depended on 15.1.3, leading to this complication. (@angular/core version conflict)

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

Issues accessing Firebase object in Angular5

After creating a sample Firebase object in the Firebase console, I tried to retrieve the object in my Typescript code. Unfortunately, following the steps outlined in this tutorial did not yield any success. Can anyone provide guidance on how to achieve thi ...

Enhancing Angular version from 5.2.7 to 5.2.10

After creating an Angular project using an older CLI version, the default installation was Angular version 5.2.7. Now, I am looking to upgrade my application to the latest stable Angular build, which is 5.2.10. One of the main challenges I'm facing i ...

Angular progress bar with dynamic behavior during asynchronous start and stop

Currently, I am facing an issue with the progress bar functionality while utilizing the ng-bootstrap module. The scenario involves a dropdown menu with multiple options, and my desired behavior includes: The ability to start/stop the progress bar indepen ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

The 'split' property is not found on the 'Int32Array' type

ERROR located in src/app/account/phone-login/phone-login.component.ts(288,53): error TS2339: Property 'split' is not a valid property for type 'string | Int32Array'. Property 'split' cannot be found on type 'Int32Array& ...

Tips for effectively transmitting data while utilizing a declarative/reactive data access method with RxJS in Angular?

Angular typically follows a classic pattern for data access that looks like this: Traditional Data Access Pattern getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.productsUrl) .pipe( tap(data => consol ...

A keyboard is pressing on tabs and navigating through the app's contents in Ionic 3 on an Android device

I'm currently working on an IONIC 3 app and facing a challenge. When I tap on the ion search and the Keyboard pops up in ANDROID, it disrupts the layout by pushing all the content around. Original screen: Keyboard mode active: Things I've tri ...

Unable to find solutions for all parameters in AngularFirestoreDocument: (?, ?)

I have integrated Angular 11 with Firebase for authentication and Firestore for data collection. However, I encountered an error message Can't resolve all parameters for AngularFirestoreDocument: (?, ?). How can I resolve this null injector issue? On ...

Tips for executing Firebase transactions involving read operations subsequent to write operations

Is there a method to incorporate read operations following write operations in nodejs for cloud and background functions? According to the information provided in the documentation, only server client libraries allow transactions with read operations afte ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Error encountered: An unexpected name token (DocumentAttributes) was found while using webpack and UglifyJs

Currently, I am working on generating word documents with images using the angular typescript code and docx 5.0.2 version. However, when utilizing webpack.optimize.UglifyJsPlugin, I encountered the following error during the code build process: Unexpected ...

Extending an External Object with Custom Properties in TypeScript

When working with an external library, I often find myself needing to add new properties to passed-in parameters. Instead of using (<any>conv.data) due to the compiler error Object is of type 'unknown', I'm curious if there's a mo ...

Getting an Ionic 2 project up and running post git clone

After successfully creating an app using Ionic 2 Beta 7, I uploaded it to Github and cloned it into a different directory. Once in the new directory, I performed npm install and ionic state restore to install dependencies and added the android platform. ...

Navigating with Tabs in Ionic Angular is a Breeze

Here is the routing configuration found in app-routing.module: const routes: Routes = [ { path: 'displayfile/:navitemid', loadChildren: () => import('./pages/file-viewer/file-viewer.module').then( m => m.FileViewerPageMo ...

When trying to use the exported Ionic 3 class in TypeScript, the error "Cannot find name 'ClassName'" occurs

When working on my Ionic 3 Application, I encountered an error stating "Cannot find name" when trying to use certain plugins. I initially imported the plugin like this: import { AndroidPermissions } from '@ionic-native/android-permissions'; and ...

Verify the login details of a distant website using Angular

Currently, I am in the process of developing a user interface for Hacker News using Angular 7. Typically, I rely on public APIs for various functionalities, but unfortunately, login services are not accessible through these APIs. In order to address this ...

Deciphering the Mysteries of API Gateway Caching

It seems like a common pattern to enable an API Gateway to serve an Angular Webapp by pulling it from S3. The setup involves having the API gateway with a GET request set up at the / route to pull index.html from the appropriate location in the S3 bucket, ...

Identifying the camera model using getMediaStream

Are there methods available to determine if a user's device has a front, rear, or dual cameras installed? For instance, laptops typically only have a front-facing camera while some devices may have both. I am looking for a way to identify the type of ...

[Nuxt.js/Typescript] Accessing Vuex data in Nuxt.js using Typescript

Hello, I am new to Typescript and I have encountered an issue with setting Objective Data to Vuex store. Here is the Objective data of Users (also known as account). # models/User.ts export interface IUser { email: string | null name: string | null ...

Calculate the variance in days between two dates and assign the result to a separate field

I am working with two date fields, one labeled Commencement Date and the other as Expiration Date. Objective: The goal is to calculate the difference in days between the selected commencement and expiration dates (expirationDate - commecementDate) and ...