I'm working on an Angular application feature where upon selecting a role, the user has a 50% chance to be redirected to screen A or screen B, determined through a feature flag. My issue is that posthog.onFeatureFlags is getting called multiple times even though the role selection logic seems to trigger only once.
// in template
<div *ngFor="let role of roles">
<app-role-card
(click)="onRoleSelected(role.role, role.roleValue)"
>
</app-role-card>
</div>
// in ts file
onRoleSelected(role: Role, roleValue: RoleValue): void {
this.postHogService.sendEvent(eventNames.slp_signup_roleSelectionComplete_NW00, {
$set: { up_signup_profile_role: role },
ep_roleSelected: role,
});
console.log('roles selected');
posthog.onFeatureFlags(() => {
console.log('onfeature flag called I am in designation comp');
const relevantFeatureFlag = this.roleToFeatureFlagMap[role];
const featureFlagPayload = getFeatureFlag(relevantFeatureFlag)
const destinationRoute = this.getDestinationRoute();
this.router.navigate([destinationRoute]);
});
}
- I see roles selected logged only once.
- The event slp_signup_roleSelectionComplete_NW00 is triggered once.
- However, onfeature flag called I am in designation comp gets logged multiple times as shown in this screenshot: The logs
for more context there is also another selection screen after this and when the user selects an option on that screen, onfeatureflag called I am in designation comp
is logged again even though I am not calling posthog.onFeatureFlags
in that component. This suggests that the posthog.onFeatureFlags in the designation
component is being re-invoked.
Heres is how posthog is setup in the project
main.ts
import { init as initPostHog } from './app/shared/postHog/posthog';
initPostHog();
in posthog.ts
export function onFeatureFlags(cb: any): void {
posthog.onFeatureFlags(cb);
}
export function init(): void {
posthog.init(environment.POSTHOG_API_KEY, {
api_host: environment.POSTHOG_API_HOST,
});
}
export function getFeatureFlag(label: string): string | boolean | undefined {
return posthog.getFeatureFlag(label);
}
export function capture(eventName: string, eventData: any): void {
if (!environment.cs) {
posthog.capture(eventName, eventData);
}
}
Any pointers on whats wrong here.
I have tried changing the detection strategy but it didn't work.
Calling the feature flags in the constructor or ngOnInit works and the function is only called once but I dont want to call multiple feature flags (one for each role) on every render and only want to call the relevant feature flag once a role is selected.
I want posthog.onFeatureFlags
to be only called once since I need to redirect the user, and if its called again at a later stage the user gets redirected again.
How do I stop it from being called again?