是否可以通过可观察的方式设置OpaqueToken? [英] Is it possible to set an OpaqueToken via an observable?

查看:111
本文介绍了是否可以通过可观察的方式设置OpaqueToken?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用可观察者在提供程序中设置opaquetoken.原因是我正在通过Http提供程序(外部JSON文件)读取值.

I'm trying to set an opaquetoken in the providers using an observable. Reason being is I'm reading the value via the Http provider (external JSON file).

这就是我想要做的

    {
        provide: SOME_OPAQUE_TOKEN,
        useFactory: (configService: ConfigService) => {
            configService.getPath('campaigns')
               .subscribe((res) => {
                   ???
               });
        },
        deps: [ConfigService],
    },

那么显然这是行不通的,但是我想知道是否存在针对此类问题的解决方案?

So obviously this wont work but I'm wondering if there is a solution for this sort of problem?

或者如果实际上有可能使用useFactory构造服务,则其中一个参数是异步检索的.

Or if its actually possible to construct a service using useFactory where one of your parameters is retrieved asynchronously.

有可能吗?

使用APP_INITIALIZER的解决方案

在AppModule中:

In AppModule:

{
  provide: APP_INITIALIZER,
  useFactory: (configService: ConfigService) => () => configService.load(),
  multi: true,
  deps: [ConfigService, Http],
},

在ConfigService中的load():

In ConfigService load():

public load(): Promise<Configuration> {
    let promise =
        this.http
            .get('config.json')
            .map(m => m.json())
            .toPromise();

    promise
        .then(config => this.appConfig = config);

    return promise;
}

一旦我们设置了appConfig,我们就可以使用它来设置OpaqueToken:

Once we set the appConfig we can use it to set the OpaqueToken:

    {
        provide: BASE_PATH,
        useFactory: (configService: ConfigService) => configService.appConfig.basePath, deps: [ConfigService],
    },

推荐答案

APP_INITIALIZER 未公开的多提供程序应该用于异步解决应用程序依赖项.

APP_INITIALIZER undocumented multi-provider is supposed to be used to resolve app dependencies asynchronously.

初始化器应该是一个返回诺言(用于异步初始化)或任何其他值(用于同步初始化)的函数.由于 APP_INITIALIZER 是多提供程序,因此可以有许多初始化程序,它们将并行执行并等待.此处.

An initializer is supposed to be a function that returns a promise (for async initialization) or any other value (for sync initialization). Since APP_INITIALIZER is multi-provider, there can be many initializers, they will be executed in parallel and awaited. The implementation is here.

可以将其定义为模块中的提供者:

It can be defined as a provider in module:

{
  provide: APP_INITIALIZER,
  useFactory: (...deps...) => () => promise,
  deps: [...deps...],
  multi: true
}

或者对于没有依赖项的初始化程序:

Or for an initializer without dependencies:

{
  provide: APP_INITIALIZER,
  useValue: () => promise,
  multi: true
}

这篇关于是否可以通过可观察的方式设置OpaqueToken?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆