Created
March 30, 2022 13:44
-
-
Save cookavich/a8d99e8fa37b11ce8e0f3592d7e1e0c7 to your computer and use it in GitHub Desktop.
LaunchDarkly feature flag service in Angular using RxJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, OnDestroy } from '@angular/core'; | |
import { environment } from '@environments/environment'; | |
import * as LaunchDarkly from 'launchdarkly-js-client-sdk'; | |
import { LDFlagValue } from 'launchdarkly-js-client-sdk'; | |
import { Observable, Subject } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class FeatureFlagService implements OnDestroy { | |
client: LaunchDarkly.LDClient; | |
async ngOnDestroy() { | |
await this.client.close(); | |
} | |
initialize(): void { | |
const user = { | |
anonymous: true | |
} as LaunchDarkly.LDUser; | |
this.client = LaunchDarkly.initialize(environment.launchDarklyClientId, user); | |
} | |
getFlag(flagKey: string, defaultValue: LDFlagValue = false): Observable<LDFlagValue> { | |
const fetchFlag = new Subject<void>(); | |
this.client.on(`change:${flagKey}`, () => { | |
fetchFlag.next(); | |
}); | |
this.client.waitUntilReady().then(() => { | |
fetchFlag.next(); | |
}); | |
return fetchFlag.pipe( | |
map(() => { | |
return this.client.variation(flagKey, defaultValue); | |
}) | |
); | |
} | |
} |
Can you provide a link of how this is used, particularly how/when you call initialize()? It would be nice to see this inside a project - initialization, consumption, etc.
@thardy it’s used in a private repo, so, I can’t link to anything live. I will look to add some more example code here.
Eventually you would want to replace the "anonymous" user with a real one. How would you do that here?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you test “this.client.on” event? Any example code will be appreciated?
https://gist.github.com/cookavich/a8d99e8fa37b11ce8e0f3592d7e1e0c7#file-feature-flag-service-ts-L27