Last active
April 30, 2025 16:45
-
-
Save jcardali/1b4b46b678b81c4dc734f2b380fbd68c to your computer and use it in GitHub Desktop.
PostHog FE implementation
This file contains hidden or 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 } from '@angular/core'; | |
import { User } from '../../models/user'; | |
import { environment } from '../../../environments/environment'; | |
import posthog, { JsonType } from 'posthog-js'; | |
import { FeatureFlagsEnum } from '../constants/feature-flags.enum'; | |
import { BehaviorSubject, Observable, of } from 'rxjs'; | |
@Injectable({ providedIn: 'root' }) | |
export class PostHogService { | |
init(): void { | |
if (!window.Cypress && (environment.production || environment.staging || environment.develop)) { | |
posthog.init(environment.POSTHOG_API_KEY, { api_host: 'https://us.i.posthog.com' }); | |
} | |
} | |
identify(user: User): void { | |
if (window.Cypress) { | |
return; | |
} | |
try { | |
posthog.identify(String(user.id), user); | |
if (user.company_posthog_groups) { | |
user.company_posthog_groups.forEach((group) => { | |
posthog.group(user.posthog_group_type, group); | |
}); | |
} | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
isFeatureEnabled(featureFlag: FeatureFlagsEnum): Observable<boolean> { | |
if (window.Cypress) { | |
return of(false); | |
} | |
const isEnabled$ = new BehaviorSubject<boolean | null>(null); | |
posthog.onFeatureFlags(() => { | |
isEnabled$.next(posthog.isFeatureEnabled(featureFlag)); | |
}); | |
return isEnabled$.asObservable(); | |
} | |
getFeatureFlagPayload(featureFlag: FeatureFlagsEnum): JsonType { | |
if (window.Cypress) { | |
return null; | |
} | |
return posthog.getFeatureFlagPayload(featureFlag); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment