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 {}