我需要使用工厂获得配置,该工厂将在应用程序初始化期间(使用APP_INITIALIZER提供程序)解决。
export function loadConfig(): () => Promise<Config> {
// return promised config
}它使用AppModule提供:
providers: [{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [HttpClient, ConfigService],
multi: true
}]然后,我需要在向另一个InjectionToken中注入一些东西时使用该配置数据,但是如果我使用应用程序初始化期间提供的配置提供特定的注入令牌,则该进程将在APP_INITIALIZER执行之前执行。
export const FORMATS = new InjectionToken<Formats>("formats")
export assignFormat(configService: ConfigService) {
return configService.getFormats(); // Needs to execute after APP_INITIALIZER, not before
}providers: [{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [HttpClient, ConfigService],
multi: true
}, {
provide: FORMATS,
useFactory: assignFormat,
deps: [ConfigService]
}]@Injectable({ providedIn: "root" })
export class ConfigService {
constructor() {}
getFormats() {}
}如何在应用程序初始化后提供注入令牌?
发布于 2021-09-22 21:01:01
如果您的loadConfig工厂返回一个函数,而不是实际的承诺,那么您在这里所拥有的应该是有效的。
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的提供与代码中的内容完全相同:
{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [ConfigService],
multi: true,
},设置下一个注入令牌时,应该可以使用该配置。
{
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一起使用的工厂,但请注意,从这些工厂中,您需要返回一个函数而不是实际值。
https://stackoverflow.com/questions/69290389
复制相似问题