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

Is Angular equipped with named routes or states similar to UIRouter?

When working with AngularJS and ui-router, we define a state like this: .state('myState', { url: 'some-user-friendly-url' ... }) This allows us to easily specify the URL and name of the state. It simplifies navigation by letting ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

When using ngModel, the Tinymce Angular 2+ templates do not initially replace values, whereas they do when templates are inserted by the user

In my Angular 7 app, I am utilizing the TinyMCE editor component. When I insert a template variable into the editor: <span class="data-variable">${variable_name}</span> The variable gets replaced successfully with a value from the `template_r ...

Which specific files do I have to edit in order for Laravel to acknowledge a new data type?

Currently, I am honing my skills in Laravel by working on a Laravel Breeze application. One task that I have set for myself is to incorporate a postal code field into the existing User model, including the registration form. To tackle this challenge, I dec ...

Loading Highcharts in Angular app

I'm currently using a highchart donut chart, but it's loading before the API response comes in. This is causing the data not to render properly. I need to retrieve the value of this.Total_connect in the highchart. Also, I want to access the val ...

Unable to access attribute of instantiated class

I am relatively new to TypeScript and I recently encountered a problem that's stumping me. I'm working on setting up a REST API using Express. The setup involves a router that calls a controller, which in turn invokes a service method before ret ...

The web server is now serving Index.html instead of main.js for AngularJS 2

Transitioning from an angular1 application to an angular2 one, I encountered an error after removing the ng-app directive and adding the system.config: Error: SyntaxError: Unexpected token < Evaluating https://localhost:8080/contents/app/main.js Error ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...

What is the best way to export an Angular application for users who do not have access to npm

Currently, I am developing an Angular application for a school assignment. The project is complete and runs smoothly on the console. Unfortunately, our instructors lack the patience and IT expertise to install NPM and run the project via the console. Is ...

Eliminate the "email address" input field from Stripe checkout in Angular 2

I am currently using Angular 2 for my project and need some help. Is there a way to remove the email address field from Stripe checkout? https://i.stack.imgur.com/auf6C.png Thank you in advance! ...

The FileSaver application generates a unique file with content that diverges from the original document

I'm attempting to utilize the Blob function to generate a file from information transmitted via a server call, encoded in base64. The initial file is an Excel spreadsheet with a length of 5,507 bytes. After applying base64 encoding (including newlines ...

Error Encountered: White screen issue affecting Ionic 6 / Angular 14 app running on Android 6.1 device without Google Mobile

After successfully deploying my new Ionic 6 / Android 14 app on multiple devices, I encountered a problem with one specific device - a Zebra ET50 running Android 6.1 without Google Mobile Services. The app fails to load and only shows a white screen. I no ...

Group Hover by StyleX

I recently experimented with the innovative StyleX library and encountered a particular challenge. Can a group hover effect be achieved for a component solely using this library? For instance, let's assume we have the following component in Tailwind ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Is there a way to trigger validation with a disabled property?

My form element is set up like this: <input type="text" id="country" formControlName="Country" /> The form group looks like this: this.myForm = this.formbuilder.group({ 'Country': [{ value: this.user.Country, disabled: this.SomeProperty= ...

"Unindexing data in Angular: A step-by-step guide

Can someone help me figure out how to delete an item by index in Angular? I have a parameter and a remove button, but when I tried putting my parameter inside the remove button it didn't work. How can I fix this? deleteRowFiles(rowIndex: number){ th ...

Encountering TypeScript errors while trying to implement Headless UI documentation

import { forwardRef } from 'react' import Link from 'next/link' import { Menu } from '@headlessui/react' const MyLink = forwardRef((props, ref) => { let { href, children, ...rest } = props return ( <Link href={href}&g ...

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...