Created
September 16, 2022 14:43
-
-
Save reyco1/cedbf994587c9dfa5511112edcfa1197 to your computer and use it in GitHub Desktop.
Angular Firebase User Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { User } from '@angular/fire/auth'; | |
import { BehaviorSubject } from 'rxjs'; | |
import { take } from 'rxjs/operators'; | |
import { AppUser } from '../models/user.model'; | |
import { DbService } from './db.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class UserService { | |
currentUser: BehaviorSubject<AppUser> = new BehaviorSubject(null); | |
constructor( | |
private db: DbService | |
) { } | |
getCurrentUser(): AppUser { | |
return this.currentUser.value; | |
} | |
async updateUserData(user: AppUser): Promise<void> { | |
return this.db.updateDocument('users/', user.id, user); | |
} | |
async getUserData(user: User): Promise<AppUser> { | |
if (!user) | |
return null; | |
const userDetails: AppUser = await this.db.getDocument('users/', user.uid).pipe(take(1)).toPromise() as AppUser; | |
if (!!userDetails) { | |
return userDetails; | |
} else { | |
const userData: AppUser = { | |
id: user.uid, | |
email: user.email, | |
displayName: user.displayName, | |
photoURL: user.photoURL, | |
emailVerified: user.emailVerified | |
}; | |
return this.db.addDocument('users/', userData, user.uid) | |
.then(() => userData); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment