Angular ResolveFn - 必须从注入上下文调用inject()

问题描述 投票:0回答:1

在尝试将 Angular 的“Resolve”类实现实例弃用为首选功能实现“ResolveFn”时,我遇到了一个令人困惑的问题。 我有一个简单的解析器正在准备我的数据。 我收到此错误,但不清楚原因: “inject() 必须从注入上下文调用,例如构造函数、工厂函数、字段初始值设定项或与

EnvironmentInjector#runInContext
一起使用的函数。”

出错的代码

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)
    ]);
};

最令人困惑的部分是,如果我只是将仪表板服务常量向上移动一行,它就可以解决问题。

工作代码

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)
    ]);
};

为什么简单地向上移动 const 就可以解决这个注入问题?

对于其他上下文,DashboardsService 和PrepareAdHocReportingService 都注入了“providedIn: 'root'”。

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

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

angular typescript inject angular-resolver
1个回答
0
投票

等待

Promise
确实有效地退出注入上下文

© www.soinside.com 2019 - 2024. All rights reserved.