我想在应用程序启动时初始化一些重要的值(Angular v17).

App.config.ts:

export const appConfig: ApplicationConfig = {
    providers: [
        ConfigService,
        ...
        {
            provide: APP_INITIALIZER,
            useFactory: (init: ConfigService) => init.load(),
            multi: true,
            deps: [ConfigService, HttpClient]
        }
    ]
};

Config.Serice.ts:

@Injectable({
    providedIn: 'root',
})
export class ConfigService {
    private http = inject(HttpClient);
    
    private _config: any;
    private _user: AppUser;
    
    public getConfigUrl(key: string): string {
        return this._config.urls[key];
    }

    public load(): Promise<any> {
        return new Promise((resolve, reject) => {
            this._user = new AppUser(); <-- normally a request to my node-express server
            this._config = 'test';
            resolve(true);
        });
    }
}

然后我在运行应用程序时遇到了这个错误,不明白为什么.

ERROR TypeError: appInits is not a function
    at \_ApplicationInitStatus.runInitializers (core.mjs:31069:32)
    at core.mjs:34973:28
    at \_callAndReportToErrorHandler (core.mjs:31146:24)
    at core.mjs:34971:20
    at \_ZoneDelegate.invoke (zone.js:368:26)
    at Object.onInvoke (core.mjs:14424:33)
    at \_ZoneDelegate.invoke (zone.js:367:52)
    at \_Zone.run (zone.js:130:43)
    at \_NgZone.run (core.mjs:14275:28)
    at internalCreateApplication (core.mjs:34948:23)

推荐答案

  1. 创建一个工厂函数如下:
export function initializeAppFactory(init: ConfigService, http: HttpClient) {
  return () => init.load();
}
  1. APP_INITIALIZER token提供工厂功能:
export const appConfig: ApplicationConfig = {
    providers: [
        ConfigService,
        ...
        {
          provide: APP_INITIALIZER,
          useFactory: initializeAppFactory,
          multi: true,
          deps: [ConfigService, HttpClient],
        }
    ]
};

参考编号:APP_INITIALIZER

Typescript相关问答推荐

您可以创建一个类型来表示打字员吗

为什么在TypScript中写入typeof someArray[number]有效?

如何为ViewContainerRef加载的Angular组件实现CanDeactivate保护?

是否可以根据嵌套属性来更改接口中属性的类型?

在Angular中注入多个BrowserModules,但在我的代码中只有一个

具有动态键的泛型类型

在MessageStore对象中实现条件类型时出现TypeScrip错误

Vue SFC中的多个脚本块共享导入的符号

如何按不能保证的功能过滤按键?

TypeScrip-将<;A、B、C和>之一转换为联合A|B|C

一个打字类型可以实现一个接口吗?

接口重载方法顺序重要吗?

ANGLING v17 CLI默认设置为独立:延迟加载是否仍需要@NgModule进行路由?

如何在Typescript 中组合unions ?

确保对象列表在编译时在类型脚本中具有唯一键

为什么发送空字段?

如何通过转换器类继承使用多态将对象从一种类型转换为另一种类型

我的类型谓词函数不能像我预期的那样工作.需要帮助了解原因

如何让Record中的每个值都有独立的类型?

使用嵌套属性和动态执行时,Typescript 给出交集而不是并集