|
1 |
| -import {Injectable} from '@angular/core'; |
2 |
| -import {Auth, GoogleAuthProvider, onIdTokenChanged, signInWithPopup, signOut, User} from '@angular/fire/auth'; |
3 |
| -import {BehaviorSubject} from 'rxjs'; |
| 1 | +import {inject, Injectable} from '@angular/core'; |
| 2 | +import {Auth, GoogleAuthProvider, idToken, user, signInWithPopup, signOut, User} from '@angular/fire/auth'; |
| 3 | +import {BehaviorSubject, Subscription} from 'rxjs'; |
4 | 4 |
|
5 | 5 | @Injectable({
|
6 | 6 | providedIn: 'root'
|
7 | 7 | })
|
8 | 8 | export class AuthService {
|
| 9 | + private auth: Auth = inject(Auth); |
| 10 | + idToken$ = idToken(this.auth); |
| 11 | + idTokenSubscription: Subscription; |
| 12 | + user$ = user(this.auth); |
| 13 | + userSubscription: Subscription; |
| 14 | + |
9 | 15 | private readonly idTokenSubject = new BehaviorSubject<string|null>(null);
|
10 | 16 | public readonly idToken = this.idTokenSubject.asObservable();
|
11 | 17 | private readonly userSubject = new BehaviorSubject<User|null>(null);
|
12 | 18 | public readonly user = this.userSubject.asObservable();
|
13 | 19 |
|
14 |
| - constructor(private afAuth: Auth) { |
15 |
| - onIdTokenChanged(afAuth, user => { |
16 |
| - if (user != null) { |
17 |
| - this.userSubject.next(user); |
18 |
| - user.getIdToken().then(idToken => { |
19 |
| - this.idTokenSubject.next(idToken); |
20 |
| - }); |
21 |
| - } else { |
22 |
| - this.userSubject.next(null); |
23 |
| - this.idTokenSubject.next(null); |
24 |
| - } |
| 20 | + constructor() { |
| 21 | + this.idTokenSubscription = this.idToken$.subscribe((token: string | null) => { |
| 22 | + console.log('idToken refreshed'); |
| 23 | + this.idTokenSubject.next(token); |
| 24 | + }); |
| 25 | + this.userSubscription = this.user$.subscribe((aUser: User | null) => { |
| 26 | + this.userSubject.next(aUser); |
25 | 27 | });
|
26 | 28 | }
|
27 | 29 |
|
28 | 30 | signInWithPopup() {
|
29 | 31 | const provider = new GoogleAuthProvider();
|
30 | 32 | provider.setCustomParameters({hd: 'docchula.com'});
|
31 |
| - return signInWithPopup(this.afAuth, provider); |
| 33 | + return signInWithPopup(this.auth, provider); |
32 | 34 | }
|
33 | 35 |
|
34 | 36 | signOut() {
|
35 |
| - return signOut(this.afAuth); |
| 37 | + return signOut(this.auth); |
36 | 38 | }
|
37 | 39 |
|
38 | 40 | }
|
0 commit comments