【问题标题】:Angular injecting custom data into services during with APP_INITIALIZER使用 APP_INITIALIZER 将自定义数据注入服务
【发布时间】:2019-08-12 00:26:10
【问题描述】:

我有一个ConfigFactory。它的工作是检索应用程序配置(外部 json 文件)并保存在ConfigService

app.module

providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: configurationFactory,
        deps: [ConfigurationService],
        multi: true
    }
]

问题:另一个 Angular 服务需要应用配置信息在它自己的构造函数中。但此时配置信息未定义(应用初始化阶段)。

现在,我尝试使用useValue = configs 创建一个 InjectionToken,因此它可以是ServiceB 中的@Inject(TEST_DATA)。但是,它似乎不起作用。

配置工厂

export const TEST_DATA = new InjectionToken<any>('TestData');

export function configurationFactory(configService: ConfigService): () => Promise<any> {
    return (): Promise<any> => {
        return new Promise((resolve, reject) => {
            http.get('externalPath').then((config) => {
                // save Config in configService
                return configService.saveConfig(config);
            }).then((config) => {
                // attempt save config. Example: config contains 'hello'
                resolve({ provide: TEST_DATA, useValue: config });
            }).catch(() => {
                reject();
            });
        });
    };
}

ServiceB 构造函数中使用 TEST_DATA

@Injectable()
export class ServiceB{

    constructor(@Inject(TEST_DATA) public data: any) {
        console.log('ServiceB', data); 
        // however this prints 'TEST_DATA'. Expected: 'hello'
    }

如何让另一个 Service 构造函数获取由APP_INITIALIZER/configurationFactory 解析的数据?

【问题讨论】:

    标签: angular


    【解决方案1】:

    有多种方法可以做到这一点。

    最简单的方法是从ConfigurationService 中公开一个可观察对象并在ServiceB 中使用它。虽然这需要ServiceBConfigurationService 声明为依赖项。

    现在,一旦配置被加载,你总是可以通过 observable 发出它。此外,您还可以更好地控制通过ConfigurationService 发出所需的值

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多