Skip to content

Instantly share code, notes, and snippets.

@cookavich
Created March 30, 2022 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cookavich/a8d99e8fa37b11ce8e0f3592d7e1e0c7 to your computer and use it in GitHub Desktop.
Save cookavich/a8d99e8fa37b11ce8e0f3592d7e1e0c7 to your computer and use it in GitHub Desktop.
LaunchDarkly feature flag service in Angular using RxJS
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);
})
);
}
}
@cookavich
Copy link
Author

@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.

@ericc6169
Copy link

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