The Angular ResolveFn error states that the inject() function must be invoked within an injection context

As I attempted to phase out Angular's "Resolve" class implementation in favor of the "ResolveFn" functional implementation, I encountered a perplexing issue. I have a basic resolver that is preparing my data. I am facing an error that has left me puzzled: "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."

Error-Prone Code

import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, ResolveFn } from '@angular/router';
import { PrepareAdHocReportingService } from '@features/reporting/services/prepare-ad-hoc-reporting.service';
import { DashboardsService } from '../dashboards.service';

export const homeDashboardResolver: ResolveFn<void> = async (
    route: ActivatedRouteSnapshot
) => {
    await inject(PrepareAdHocReportingService).resolve();
    const dashboardsService = inject(DashboardsService);
    await Promise.all([
      dashboardsService.fetchWidgets(),
      dashboardsService.getDashboardDetail(route.params.id)
    ]);
};

The intriguing part is that moving the declaration of the dashboardsService const up by just ONE line resolves the issue.

Working Code

import { ActivatedRouteSnapshot, ResolveFn } from '@angular/router';
import { PrepareAdHocReportingService } from '@features/reporting/services/prepare-ad-hoc-reporting.service';
import { DashboardsService } from '../dashboards.service';

export const homeDashboardResolver: ResolveFn<void> = async (
    route: ActivatedRouteSnapshot
) => {
    const dashboardsService = inject(DashboardsService);
    await inject(PrepareAdHocReportingService).resolve();
    await Promise.all([
        dashboardsService.fetchWidgets(),
        dashboardsService.getDashboardDetail(route.params.id)
    ]);
};

Why does shifting the const declaration up line fix this injection issue?

To provide more context, both DashboardsService and PrepareAdHocReportingService are injected with "providedIn: 'root'".

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

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

Answer â„–1

When waiting for a Promise, it effectively exits the injection context.

To continue running within the injection context, you must use runInInjectorContext after the await statement.

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

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Utilize the ngClass directive in conjunction with ngFor loop functionality

Currently, I am working on rendering a list of elements using the *ngFor directive in Angular. However, I have encountered an issue where only certain parts of the text within the list items should be bold based on specified requirements. I attempted to ac ...

Encountered a XHR error (404) while attempting to load the script from https://unpkg.com/[email protected]/operators/index.js/first

Struggling with implementing the Google Material input control in angular2, I keep encountering a recurring error in the browser console. https://i.stack.imgur.com/Q5YFA.png: Upon inspecting my 'node_modules' directory, I noticed the presence o ...

Reach out to the property via phone if it is listed in the JSON

When receiving JSON data from the server, I come across two different structures: JSON 1: { [{ name : 'sample1', code:'sample code 1', data : { display :'test' } ...

Is it recommended to keep Angular properties private and only access them through methods?

I'm starting to get a bit confused with Angular/Typescripting. I originally believed that properties should be kept private to prevent external alteration of their values. Take this example: export class Foo{ private _bar: string; constructor(pr ...

Invoke an RxJs observable to handle errors and retry the process

I have an observable called submit$ that submits a form. If this observable encounters an error with status code 403, it means the user is not authorized and needs to log in first. Is there a way to automatically trigger another observable when a specific ...

Clearing error messages from a form using the reset button or after cancelling the form

I am having trouble removing the error outline around the input box and error messages displayed below it. When I cancel the form or click on the reset button, the input fields' content along with the error messages should be cleared. However, current ...

The 'fullDocument' property is not present in the 'ChangeStreamDropDocument' type

Upon cloning an express TypeScript project, I encountered a Typescript error within a Mongo related function as mentioned in the title. Property 'fullDocument' does not exist on type 'ChangeStreamDocument<IUser>'. Property &apos ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

Serve both .ts and .js files to the browser using RequireJs

In my ASP.NET Core Project, the following files are present: greet.ts export class WelcomMesssage { name: string; constructor(name: string) { this.name = name; } say(): void { console.log("Welcome " + this.name); } } GreetExample.ts import * as ...

Guidance on transferring information from a parent component to an Angular Material table child component

Currently, I am implementing an angular material table with sorting functionality. You can view the example here: Table Sorting Example I intend to transform this into a reusable component so that in the parent component, all I have to do is pass the colu ...

Having trouble accessing a JSON object with Typescript in an Angular 2 project

Something strange is happening with my code. I am working with a JSON object: {"login":"admin","name":"Admin"} And this is the relevant part of my code: private _userData: User; ... private getUserData() { this._userInfoService.getUserInfo() ...

PDFJS integration in Ionic 2

Looking for guidance on integrating pdfjs into an ionic2 project. Any suggestions on how to import and use it would be greatly appreciated. Thank you! I'm familiar with using pdfjs, but I'm having trouble figuring out how to bring it into my ion ...

Error encountered during Angular ahead-of-time (AOT) compilation: Internal state issue - Summaries cannot contain members in StaticSymbols

Our team is currently working on implementing ahead of time (AOT) compilation for our Angular 2 project, but we have encountered an error: Error: Internal state: StaticSymbols in summaries can't have members! {"filePath":"C:/Users/bhavy/Documents/p ...

Substituting generic type in inherited class method results in error message: "Property 'x' in type 'y' cannot be assigned to the property with the same name in the base class 'Parent'."

Here is the code snippet I am working with: class BaseModel { protected getAttribute<T extends BaseModel>(): keyof T | null { return null; } } class Payment extends BaseModel {} class Item extends BaseModel {} class Sale extends BaseModel { ...

Issue when calling .create() method on Mongoose schema: "this expression is not callable" error in TypeScript

Encountering an error with the .create method on a mongoose model in Next JS while making a call in an API route. The get request is functioning properly... The structure: pages>API>task.tsx import dbConnect from "../../util/dbconnect"; im ...

Merging multiple observables with RxJs forkJoin

UPDATE : I'm currently facing a challenging issue that I can't seem to resolve. Within my code, there is a list of objects where I need to execute 3 requests sequentially for each object, but these requests can run in parallel for different obje ...

Issue with MUI Select custom MenuItem functionality not functioning as expected

Having an issue with MUI's MenuItem in conjunction with Select and rendering it within a separate component. Check out the codesandbox for reference. The setup is as follows: import { Select } from "@material-ui/core"; import CustomMenuIte ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

Decorators do not allow function calls, yet the function 'AngularSignaturePadModule' was invoked

Currently, I'm facing a problem with Angular Signature Pad. Specifically, there seems to be an issue with this particular line of code: AngularSignaturePadModule.forRoot(), ERROR in Error during template compile of 'AppModule' Function ...