I am integrating a feature toggle service called launch darkly into my Angular application. I followed the guidance here: https://launchdarkly.com/blog/integrating-feature-flags-in-angular-v4/
However I noticed that on occasion my application would render on screen before fetching the flags. I want the flags to always be accurate, so I used the APP_Initializer to ensure the launchdarkly.service.ts loaded the flags before loading the rest of my application.
app.module.ts
LaunchDarklyService,
{
provide: APP_INITIALIZER,
useFactory: function(launchDarklyService: LaunchDarklyService) {
async function asyncLaunchDarklyInitializer(): Promise<void> {
await launchDarklyService.initializeFlags();
}
return (asyncLaunchDarklyInitializer);
},
deps: [LaunchDarklyService],
multi: true
}
This worked fine, using the sample user key.
this.ldClient = initialize("YOUR-CLIENT-SIDE-ID",
{ key: "SAMPLE-USER-KEY", anonymous: true });
However to populate the launchdarkly.service.ts with a user key to identify my users I need to inject my user.service.ts.
When I try to do that the application fails to initialize and I get an error 'Invalid user specified.'. I suspect the user service is not loading correctly before my launchdarkly service, leaving me with an undefined user.
How can I get the user Id from my user service, into my launch darkly service before the application initializes?
My user service has the following function
async getUserId(): Promise<string> {
if (this.isTest)) {
return this.$storage.read(StorageTypes.LOCAL, 'testId')
}
return (await this.$auth.getIdToken())?.userId;
}
I have tried adding my user service as another App_initializer but that didn't work. I then tried to add two promises to my App_Initializer but that didn't work either
LaunchDarklyService,
{
provide: APP_INITIALIZER,
useFactory: function(userService: UserService,launchDarklyService: LaunchDarklyService) {
async function asyncUserIdInitializer(): Promise<void> {
await userService.getUserId();
}
async function asyncLaunchDarklyInitializer(): Promise<void> {
await launchDarklyService.initializeFlags();
}
// return (asyncLaunchDarklyInitializer);
async function load(): Promise<void>{
await Promise.all([asyncUserGuidInitializer(), asyncLaunchDarklyInitializer()]);
}
return (load);
},
deps: [LaunchDarklyService, UserService],
multi: true
}
And I tried creating a function in my launch darkly service to await a promise from my user service but that didn't work either.
async getUserID(): Promise<void>{
await this._userService.getUserGuid().then(res => {this.userID = res.toString();})
}
Everything I try results in my application failing to load due to the launchdarkly service not initializing correctly.