Search code examples
angularfirebaseangularfire2firebase-analytics

How to set custom dimension values using AngularFireAnalytics?


I'm using @angular/fire (version 5.3.0) and its AngularFireAnalytics module for Firebase Analytics. It works great! Except I cannot find a way to set values for custom dimensions, which we need in our solution.

We also need to set these values dynamically, rather than once during initialization, as the values change during usage of the app.

Does anyone know if there is a hook I can implement that will let me set custom dimension values before the page_view event is sent by AngularFireAnalytics?


Solution

  • I found a way to do this.

    Import the following:

    import { NgZone } from '@angular/core';
    import { AngularFireAnalytics } from '@angular/fire/analytics';
    

    Inject both NgZone and AngularFireAnalytics into your component:

    constructor(
        private zone: NgZone,
        private analytics: AngularFireAnalytics
    ) { }
    

    and then, in an async method, call:

    await this.zone.runOutsideAngular(async () => {
       await this.analytics.setUserProperties({
            my_custom_prop: custom_prop_value,
            another_prop: other_prop_value
        });
    });
    

    This will set the properties for all subsequent events.