-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathuser-tracking.service.ts
More file actions
45 lines (41 loc) · 1.52 KB
/
user-tracking.service.ts
File metadata and controls
45 lines (41 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { Injectable, Injector, NgZone, OnDestroy } from '@angular/core';
import { VERSION } from '@angular/fire';
import { Auth, authState } from '@angular/fire/auth';
import { registerVersion } from 'firebase/app';
import { Subscription } from 'rxjs';
import { Analytics } from './analytics';
import { isSupported, setUserId } from './firebase';
@Injectable()
export class UserTrackingService implements OnDestroy {
public readonly initialized: Promise<void>;
private disposables: Subscription[] = [];
constructor(
auth: Auth,
zone: NgZone,
injector: Injector,
) {
registerVersion('angularfire', VERSION.full, 'user-tracking');
let resolveInitialized: () => void;
this.initialized = zone.runOutsideAngular(() => new Promise(resolve => { resolveInitialized = resolve; }));
// The APP_INITIALIZER that is making isSupported() sync for the sake of convenient DI
// may not be done when services are initialized. Guard the functionality by first ensuring
// that the (global) promise has resolved, then get Analytics from the injector.
isSupported().then(() => {
const analytics = injector.get(Analytics);
if (analytics) {
this.disposables = [
// TODO add credential tracking back in
authState(auth).subscribe(user => {
setUserId(analytics, user?.uid);
resolveInitialized();
}),
];
} else {
resolveInitialized();
}
});
}
ngOnDestroy() {
this.disposables.forEach(it => it.unsubscribe());
}
}