Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
e5be927
Firebase v7, analytics and remote-config
jamesdaniels Oct 2, 2019
1cf961b
Cleaning up the DI tokens
jamesdaniels Oct 2, 2019
f5f67ad
Cleaning things up
jamesdaniels Oct 4, 2019
73413e8
DI and jazz
jamesdaniels Oct 4, 2019
dd0efb1
Bumping the tests
jamesdaniels Nov 8, 2019
dffca53
Adding to the root-spec
jamesdaniels Nov 9, 2019
9731e3c
Spelling is good.
jamesdaniels Nov 9, 2019
7308f9c
Merge branch 'master' into firebase-v7
jamesdaniels Nov 9, 2019
dcdf8bc
Have to include UMDs in the karma.conf
jamesdaniels Nov 9, 2019
6f71d46
Just importing performance is destablizing the app
jamesdaniels Nov 11, 2019
6638b9d
Merge branch 'master' into firebase-v7
jamesdaniels Nov 12, 2019
d7d52c8
Adding the zone arg to the app factory
jamesdaniels Nov 12, 2019
eb4bc00
First pass on the new RC API and the start of the AngularFireLazy effort
jamesdaniels Nov 13, 2019
89344cc
Update src/remote-config/tsconfig-test.json
jamesdaniels Nov 14, 2019
075afe6
Reworking things a bit
jamesdaniels Nov 20, 2019
b8b351a
Router as optional, drop this/private from screen tracking
jamesdaniels Nov 20, 2019
1e39052
Minor changes to RC
jamesdaniels Nov 20, 2019
768c21b
It's firebase_screen_class
jamesdaniels Nov 21, 2019
60c0cad
Reworking analytics
jamesdaniels Nov 22, 2019
9b2e920
current!
jamesdaniels Nov 22, 2019
916e069
Use _loadedConfig if available and scope screen_id on outlet
jamesdaniels Nov 22, 2019
5955925
Fixing the types to handle older Firebase SDKs
jamesdaniels Nov 22, 2019
659165e
SEMVER notes on the DI tokens
jamesdaniels Nov 22, 2019
62d90b9
Starting on the docs
jamesdaniels Nov 22, 2019
1a43ad1
Merge branch 'firebase-v7' of github.com:angular/angularfire2 into fi…
jamesdaniels Nov 22, 2019
67e1b55
Monitoring...
jamesdaniels Dec 9, 2019
91778ff
More work on analytics
jamesdaniels Dec 11, 2019
460170c
more expirimentation
jamesdaniels Dec 12, 2019
3c1ad1f
Flushing out RC more and fixing SSR issues
jamesdaniels Dec 14, 2019
e2d83c8
New RC API
jamesdaniels Dec 16, 2019
4601932
Mapping to objects and templates, budget pipe
jamesdaniels Dec 17, 2019
7fe92ed
More strict types
jamesdaniels Dec 17, 2019
d47dc3f
Fix proxy in Node, get component name for analytics in both JIT and AOT
jamesdaniels Dec 21, 2019
05c840b
Cleaning things up, beyond docs ready for release
jamesdaniels Jan 7, 2020
b46b382
Docs and cleanup
jamesdaniels Jan 7, 2020
ff65db8
Fixing analytics spec
jamesdaniels Jan 7, 2020
baaeccf
Adding more API to the docs
jamesdaniels Jan 7, 2020
04a3bb1
Further simplifications to the DI tokens
jamesdaniels Jan 7, 2020
c37fcb7
Add Analytics and RemoteConfig to install-and-setup
jamesdaniels Jan 7, 2020
6753a67
Merge branch 'master' into firebase-v7
jamesdaniels Jan 7, 2020
6f114c6
Our RC Value implements a Partial, so minors dont break
jamesdaniels Jan 7, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Reworking things a bit
  • Loading branch information
jamesdaniels committed Nov 20, 2019
commit 075afe66d4c75c336ca3f378b401909858c9ef24
15 changes: 8 additions & 7 deletions src/analytics/analytics.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { NgModule } from '@angular/core';
import { NgModule, Optional } from '@angular/core';
import { UserTrackingService, ScreenTrackingService } from './analytics.service';
import { AngularFireAnalytics } from './analytics';

@NgModule({
providers: [ AngularFireAnalytics ]
})
@NgModule()
export class AngularFireAnalyticsModule {
constructor(_: AngularFireAnalytics) {
// DI inject Analytics here for the automatic data collection
}
constructor(
analytics: AngularFireAnalytics,
@Optional() screenTracking: ScreenTrackingService,
@Optional() userTracking: UserTrackingService
) { }
}
100 changes: 100 additions & 0 deletions src/analytics/analytics.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { Injectable, Inject, Optional, NgZone, OnDestroy, InjectionToken } from '@angular/core';
import { Subscription, from, Observable, empty } from 'rxjs';
import { filter, withLatestFrom, switchMap, map, tap } from 'rxjs/operators';
import { Router, NavigationEnd, ActivationEnd } from '@angular/router';
import { runOutsideAngular, _lazySDKProxy, _firebaseAppFactory } from '@angular/fire';
import { AngularFireAnalytics } from './analytics';
import { User } from 'firebase/app';

export const AUTOMATICALLY_SET_CURRENT_SCREEN = new InjectionToken<boolean>('angularfire2.analytics.setCurrentScreen');
export const AUTOMATICALLY_LOG_SCREEN_VIEWS = new InjectionToken<boolean>('angularfire2.analytics.logScreenViews');
export const APP_VERSION = new InjectionToken<string>('angularfire2.analytics.appVersion');
export const APP_NAME = new InjectionToken<string>('angularfire2.analytics.appName');

const DEFAULT_APP_VERSION = '?';
const DEFAULT_APP_NAME = 'Angular App';

@Injectable({
providedIn: 'root'
})
export class ScreenTrackingService implements OnDestroy {

private disposable: Subscription|undefined;

constructor(
private analytics: AngularFireAnalytics,
private router:Router,
@Optional() @Inject(AUTOMATICALLY_SET_CURRENT_SCREEN) private automaticallySetCurrentScreen:boolean|null,
@Optional() @Inject(AUTOMATICALLY_LOG_SCREEN_VIEWS) private automaticallyLogScreenViews:boolean|null,
@Optional() @Inject(APP_VERSION) private providedAppVersion:string|null,
@Optional() @Inject(APP_NAME) private providedAppName:string|null,
private zone: NgZone
) {
if (this.automaticallySetCurrentScreen !== false || this.automaticallyLogScreenViews !== false) {
const app_name = this.providedAppName || DEFAULT_APP_NAME;
const app_version = this.providedAppVersion || DEFAULT_APP_VERSION;
const activationEndEvents = this.router.events.pipe(filter<ActivationEnd>(e => e instanceof ActivationEnd));
const navigationEndEvents = this.router.events.pipe(filter<NavigationEnd>(e => e instanceof NavigationEnd));
this.disposable = navigationEndEvents.pipe(
withLatestFrom(activationEndEvents),
switchMap(([navigationEnd, activationEnd]) => {
const url = navigationEnd.url;
const screen_name = activationEnd.snapshot.routeConfig && activationEnd.snapshot.routeConfig.path || url;
const outlet = activationEnd.snapshot.outlet;
const component = activationEnd.snapshot.component;
const ret = new Array<Promise<void>>();
if (this.automaticallyLogScreenViews !== false) {
if (component) {
const screen_class = component.hasOwnProperty('name') && (component as any).name || component.toString();
ret.push(this.analytics.logEvent("screen_view", { app_name, screen_class, app_version, screen_name, outlet, url }));
} else if (activationEnd.snapshot.routeConfig && activationEnd.snapshot.routeConfig.loadChildren) {
ret.push((activationEnd.snapshot.routeConfig.loadChildren as any)().then((child:any) => {
const screen_class = child.name;
console.log("logEvent", "screen_view", { app_name, screen_class, app_version, screen_name, outlet, url });
return this.analytics.logEvent("screen_view", { app_name, screen_class, app_version, screen_name, outlet, url });
}));
} else {
ret.push(this.analytics.logEvent("screen_view", { app_name, app_version, screen_name, outlet, url }));
}
}
if (this.automaticallySetCurrentScreen !== false) {
ret.push(this.analytics.setCurrentScreen(screen_name || url, { global: outlet == "primary" }));
}
return Promise.all(ret);
}),
runOutsideAngular(this.zone)
).subscribe();
}
}

ngOnDestroy() {
if (this.disposable) { this.disposable.unsubscribe(); }
}

}

@Injectable({
providedIn: 'root'
})
export class UserTrackingService implements OnDestroy {

private disposable: Subscription|undefined;

// TODO a user properties injector
constructor(
analytics: AngularFireAnalytics,
zone: NgZone
) {
this.disposable = from(analytics.app).pipe(
// TODO can I hook into auth being loaded...
map(app => app.auth()),
switchMap(auth => auth ? new Observable<User>(auth.onAuthStateChanged.bind(auth)) : empty()),
switchMap(user => analytics.setUserId(user ? user.uid : null!, { global: true })),
runOutsideAngular(zone)
).subscribe();
}

ngOnDestroy() {
if (this.disposable) { this.disposable.unsubscribe(); }
}
}
77 changes: 12 additions & 65 deletions src/analytics/analytics.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
import { Injectable, Inject, Optional, NgZone, InjectionToken } from '@angular/core';
import { Observable, from } from 'rxjs';
import { map, tap, filter, withLatestFrom, shareReplay } from 'rxjs/operators';
import { Router, NavigationEnd, ActivationEnd } from '@angular/router';
import { of } from 'rxjs';
import { map, tap, shareReplay, switchMap } from 'rxjs/operators';
import { FirebaseAppConfig, FirebaseOptions, runOutsideAngular, _lazySDKProxy, FirebaseAnalytics, FIREBASE_OPTIONS, FIREBASE_APP_NAME, _firebaseAppFactory } from '@angular/fire';
import { analytics, app } from 'firebase';

export const AUTOMATICALLY_SET_CURRENT_SCREEN = new InjectionToken<boolean>('angularfire2.analytics.setCurrentScreen');
export const AUTOMATICALLY_LOG_SCREEN_VIEWS = new InjectionToken<boolean>('angularfire2.analytics.logScreenViews');
export const ANALYTICS_COLLECTION_ENABLED = new InjectionToken<boolean>('angularfire2.analytics.analyticsCollectionEnabled');
export const AUTOMATICALLY_TRACK_USER_IDENTIFIER = new InjectionToken<boolean>('angularfire2.analytics.trackUserIdentifier');
export const APP_VERSION = new InjectionToken<string>('angularfire2.analytics.appVersion');
export const APP_NAME = new InjectionToken<string>('angularfire2.analytics.appName');

export const DEFAULT_APP_VERSION = '?';
export const DEFAULT_APP_NAME = 'Angular App';

// SEMVER: once we move to Typescript 3.6 use `PromiseProxy<analytics.Analytics>`
type AnalyticsProxy = {
Expand All @@ -29,74 +20,30 @@ type AnalyticsProxy = {

export interface AngularFireAnalytics extends AnalyticsProxy {};

@Injectable()
@Injectable({
providedIn: "root"
})
export class AngularFireAnalytics {

/**
* Firebase Analytics instance
*/
private readonly analytics$: Observable<FirebaseAnalytics>;
private get analytics() { return this.analytics$.toPromise(); }

constructor(
@Inject(FIREBASE_OPTIONS) options:FirebaseOptions,
@Optional() @Inject(FIREBASE_APP_NAME) nameOrConfig:string|FirebaseAppConfig|null|undefined,
@Optional() router:Router,
@Optional() @Inject(AUTOMATICALLY_SET_CURRENT_SCREEN) automaticallySetCurrentScreen:boolean|null,
@Optional() @Inject(AUTOMATICALLY_LOG_SCREEN_VIEWS) automaticallyLogScreenViews:boolean|null,
@Optional() @Inject(ANALYTICS_COLLECTION_ENABLED) analyticsCollectionEnabled:boolean|null,
@Optional() @Inject(AUTOMATICALLY_TRACK_USER_IDENTIFIER) automaticallyTrackUserIdentifier:boolean|null,
@Optional() @Inject(APP_VERSION) providedAppVersion:string|null,
@Optional() @Inject(APP_NAME) providedAppName:string|null,
zone: NgZone
) {
// @ts-ignore zapping in the UMD in the build script
const requireAnalytics = from(import('firebase/analytics'));
const app = _firebaseAppFactory(options, zone, nameOrConfig);

this.analytics$ = requireAnalytics.pipe(
map(() => app.analytics()),
const analytics = of(undefined).pipe(
// @ts-ignore zapping in the UMD in the build script
switchMap(() => zone.runOutsideAngular(() => import('firebase/analytics'))),
map(() => _firebaseAppFactory(options, zone, nameOrConfig)),
map(app => app.analytics()),
tap(analytics => {
if (analyticsCollectionEnabled === false) { analytics.setAnalyticsCollectionEnabled(false) }
}),
runOutsideAngular(zone),
shareReplay(1)
);

if (router && (automaticallySetCurrentScreen !== false || automaticallyLogScreenViews !== false)) {
const app_name = providedAppName || DEFAULT_APP_NAME;
const app_version = providedAppVersion || DEFAULT_APP_VERSION;
const activationEndEvents = router.events.pipe(filter<ActivationEnd>(e => e instanceof ActivationEnd));
const navigationEndEvents = router.events.pipe(filter<NavigationEnd>(e => e instanceof NavigationEnd));
navigationEndEvents.pipe(
withLatestFrom(activationEndEvents, this.analytics$),
tap(([navigationEnd, activationEnd, analytics]) => {
const url = navigationEnd.url;
const screen_name = activationEnd.snapshot.routeConfig && activationEnd.snapshot.routeConfig.path || undefined;
const outlet = activationEnd.snapshot.outlet;
if (automaticallyLogScreenViews !== false) {
analytics.logEvent("screen_view", { app_name, app_version, screen_name, outlet, url });
}
if (automaticallySetCurrentScreen !== false) {
// TODO when is screen_name undefined?
analytics.setCurrentScreen(screen_name || url, { global: outlet == "primary" });
}
}),
runOutsideAngular(zone)
).subscribe();
}

// TODO do something other than just check auth presence, what if it's lazy loaded?
if (app.auth && automaticallyTrackUserIdentifier !== false) {
new Observable<firebase.User|null>(app.auth().onAuthStateChanged.bind(app.auth())).pipe(
withLatestFrom(this.analytics$),
tap(([user, analytics]) => analytics.setUserId(user ? user.uid : null!, { global: true })),
runOutsideAngular(zone)
).subscribe()
}

return _lazySDKProxy(this, this.analytics, zone);

return _lazySDKProxy(this, analytics, zone);
}

}
}
1 change: 1 addition & 0 deletions src/analytics/public_api.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './analytics';
export * from './analytics.module';
export * from './analytics.service';
4 changes: 2 additions & 2 deletions src/core/angularfire2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ export const runInZone = (zone: NgZone) => <T>(obs$: Observable<T>): Observable<
{ [K in PromiseReturningFunctionPropertyNames<T> ]: (...args: Parameters<T[K]>) => ReturnType<T[K]> };
*/

export const _lazySDKProxy = (klass: any, promise: Promise<any>, zone: NgZone) => new Proxy(klass, {
export const _lazySDKProxy = (klass: any, observable: Observable<any>, zone: NgZone) => new Proxy(klass, {
get: (_, name) => zone.runOutsideAngular(() =>
klass[name] || new Proxy(() =>
promise.then(mod => {
observable.toPromise().then(mod => {
const ret = mod[name];
// TODO move to proper type guards
if (typeof ret == 'function') {
Expand Down
5 changes: 1 addition & 4 deletions src/remote-config/remote-config.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { NgModule } from '@angular/core';
import { AngularFireRemoteConfig } from './remote-config';

@NgModule({
providers: [ AngularFireRemoteConfig ]
})
@NgModule()
export class AngularFireRemoteConfigModule { }
Loading