如何在 Angular 模块的 forRoot 中注入配置

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

我们有一个相当复杂的角度应用程序,需要在加载时加载配置。我们通过使用填充在

InjectionToken
中的
main.ts
来实现此目的:

fetch('./config/config.json')
    .then((resp) => resp.json())
    .then((config) => {
        if (config.production) {
            enableProdMode();
            if (window && config.removeConsole) {
                window.console.log = function () {};
            }
        }
        platformBrowserDynamic([{ provide: APP_CONFIG, useValue: config }])
            .bootstrapModule(AppModule)
            .catch((err) => console.error(err));
    });

在AppModule中我们可以读取一些配置。对于我们的身份验证服务,这是通过添加

InjectionToken
作为依赖项来完成的:

providers: [
        {
            provide: APP_INITIALIZER,
            useFactory: initializeKeycloak,
            multi: true,
            deps: [KeycloakService, APP_CONFIG],
        },
]

但是我们还依赖于为供应商模块(Intercom)注入 AppId,我对此无法理解。

有人可以指导我如何将配置注入到 Root 模块中吗?

imports: [
        IntercomModule.forRoot({
            appId: config.intercom.appId, /// Need a reference for config here?
            updateOnRouterChange: true,
        }),
    ],

是否可以使用提供商以某种方式解决这个问题?问题是该模块来自供应商,不幸的是我们无法更改。

angular dependency-injection
1个回答
0
投票

定义一个空的 const,它将由

APP_INITIALIZER
填充,您还可以定义配置可以在此处使用的默认属性!

export let configPlaceholder: any = {};

然后您可以将配置设置在

platformBrowserDynamic
部分上方,或者在自定义
useFactory
内设置为此 const 变量

方法1

fetch('./config/config.json')
    .then((resp) => resp.json())
    .then((config) => {
        if (config.production) {
            enableProdMode();
            if (window && config.removeConsole) {
                window.console.log = function () {};
            }
        }
        configPlaceholder = config;
        platformBrowserDynamic([{ provide: APP_CONFIG, useValue: config }])
            .bootstrapModule(AppModule)
            .catch((err) => console.error(err));
    });

方法2

providers: [
        {
            provide: APP_INITIALIZER,
            useFactory: (config: any) => {
                configPlaceholder = config;
            },
            multi: true,
            deps: [APP_CONFIG],
        },
]

最后,将此变量连接到

forRoot

imports: [
    IntercomModule.forRoot({
        appId: configPlaceholder?.intercom?.appId, /// Need a reference for config here?
        updateOnRouterChange: true,
    }),
],
© www.soinside.com 2019 - 2024. All rights reserved.