我需要使用一个工厂来获取配置,该工厂将在APP初始化过程中解析(使用APP_INITIALIZER提供程序)。
export function loadConfig(): () => Promise<Config> {
// return promised config
}
这是使用AppModule提供的:
providers: [{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [HttpClient, ConfigService],
multi: true
}]
然后,我需要使用该配置数据在另一个InjectionToken中注入一些东西,但如果我使用应用程序初始化期间提供的配置提供特定的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() {}
}
如何在APP初始化后提供注入令牌?
如果您的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],
},
Angular中唯一允许的异步工厂是与APP_INITIALIZER
注入令牌一起使用的工厂,但请注意,从这些工厂中,您需要返回一个函数,而不是实际值。