首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用解析的配置在APP_INITIALIZATION之后提供一个APP_INITIALIZATION

使用解析的配置在APP_INITIALIZATION之后提供一个APP_INITIALIZATION
EN

Stack Overflow用户
提问于 2021-09-22 19:43:47
回答 1查看 995关注 0票数 1

我需要使用工厂获得配置,该工厂将在应用程序初始化期间(使用APP_INITIALIZER提供程序)解决。

代码语言:javascript
复制
export function loadConfig(): () => Promise<Config> {
    // return promised config
}

它使用AppModule提供:

代码语言:javascript
复制
providers: [{
  provide: APP_INITIALIZER,
  useFactory: loadConfig,
  deps: [HttpClient, ConfigService],
  multi: true
}]

然后,我需要在向另一个InjectionToken中注入一些东西时使用该配置数据,但是如果我使用应用程序初始化期间提供的配置提供特定的注入令牌,则该进程将在APP_INITIALIZER执行之前执行。

代码语言:javascript
复制
export const FORMATS = new InjectionToken<Formats>("formats")

export assignFormat(configService: ConfigService) {
    return configService.getFormats(); // Needs to execute after APP_INITIALIZER, not before
}
代码语言:javascript
复制
providers: [{
  provide: APP_INITIALIZER,
  useFactory: loadConfig,
  deps: [HttpClient, ConfigService],
  multi: true
}, {
  provide: FORMATS,
  useFactory: assignFormat,
  deps: [ConfigService]
}]
代码语言:javascript
复制
@Injectable({ providedIn: "root" })
export class ConfigService {
    constructor() {}
    getFormats() {}
}

如何在应用程序初始化后提供注入令牌?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-22 21:01:01

如果您的loadConfig工厂返回一个函数,而不是实际的承诺,那么您在这里所拥有的应该是有效的。

代码语言:javascript
复制
const loadConfig = (configService: ConfigService) => {
  return () =>
    new Promise<void>((resolve, reject) => {
      // I added the timeout to simulate a delay
      setTimeout(() => {
        // you might be using a http call to get the config from the server instead.
        // Make sure you keep the config that you fetched in the service;
        // this way you can inject the service in the next factory function 
        // and have the config available
        configService.config = {
          formats: 'formats',
        };
        resolve();
      }, 1000);
    });
};

APP_INITIALIZER的提供与代码中的内容完全相同:

代码语言:javascript
复制
{
  provide: APP_INITIALIZER,
  useFactory: loadConfig,
  deps: [ConfigService],
  multi: true,
},

设置下一个注入令牌时,应该可以使用该配置。

代码语言:javascript
复制
{
  provide: FORMATS,
  useFactory: (configService: ConfigService) => {
    // getFormats method must not be async, it needs to return the actual 
    // formats that were fetched during the app initialization phase
    return configService.getFormats();
  },
  deps: [ConfigService],
},

唯一允许在角中使用的异步工厂是与APP_INITIALIZER injection token一起使用的工厂,但请注意,从这些工厂中,您需要返回一个函数而不是实际值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69290389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档