我需要使用工厂获取配置,该工厂将在应用程序初始化期间解析(使用 APP_INITIALIZER 提供程序)。
export function loadConfig(): () => Promise<Config> {
// return promised config
}
这是使用 AppModule 提供的:
providers: [{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [HttpClient, ConfigService],
multi: true
}]
然后我需要使用该配置数据在另一个 InjectionToken 中注入(inject)某些内容,但是如果我使用应用程序初始化期间提供的配置提供特定的注入(inject) token ,则该过程将在 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初始化后如何提供注入(inject)token?
最佳答案
如果您的 loadConfig
工厂返回一个函数而不是实际的 promise ,那么您这里的内容应该确实有效:
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,
},
当您设置下一个注入(inject) token 时,您应该可以使用配置
{
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
injection token 一起使用的工厂。 ,但请注意,您需要返回一个函数而不是实际值。
关于angular - 在 APP_INITIALIZATION 之后使用已解析的配置提供 InjectionToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69290389/