Angular2 Firebase Get Current User
Solution 1
AngularFire2
package has been deprecated. Instead use @angular/fire
. I am using following code in my service and component.
auth.service.ts service file
authState: any = null;
constructor(
private firebaseAuth: AngularFireAuth,
) {
this.firebaseAuth.authState.subscribe( authState => {
this.authState = authState;
});
}
check if user is authenticated
get isAuthenticated(): boolean {
return this.authState !== null;
}
Check if email is verified. In case you want to send email or enable disable send email button
get isEmailVerified(): boolean {
return this.isAuthenticated ? this.authState.emailVerified : false;
}
Current user id
get currentUserId(): string {
return this.isAuthenticated ? this.authState.uid : null;
}
Get user data
get userData(): any {
if ( ! this.isAuthenticated ) {
return [];
}
return [
{
id: this.authState.uid,
displayName: this.authState.displayName,
email: this.authState.email,
phoneNumber: this.authState.phoneNumber,
photoURL: this.authState.photoURL,
}
];
}
header.component.ts component file
constructor(
private auth: AuthService
) {}
header.component.html component file
<a href="#" *ngIf="auth.isAuthenticated" (click)="auth.signout($event)">Sign Out</a>
Solution 2
I would add a subscription to firebase authentication in CustomersService
as well. By doing so, we are making sure that current user Id is available.
constructor(
private af: AngularFire,
private router: Router) {
this.af.auth.subscribe(auth => {
if(auth) {
this.usersCustomerId = auth.uid;
}
})
}
or
constructor(
private af: AngularFire,
private authService: AuthenticationService,
private router: Router) {
this.usersCustomerId = this.authService.userKey;
}
Solution 3
After long research I found this solution, in my opinion it is the best: In your Authentication Service
async getUserIDAsync() {
const user = await this.af.authState.pipe(first()).toPromise();
console.log(user);
return user.uid;
}
In your Customer Service
getAllCustomers(): FirebaseListObservable<CustomerModel[]> {
const uid = await this.authService.getUserIDAsync();
console.log(uid);
return this.af.database.list(this.customersRef, {
query: {
orderByChild: 'uid',
equalTo: uid
}
});
}
I find it much easier to handle these situations with Promises because they are NOT streams, but rather simple one-off operations.
ccocker
Updated on July 01, 2022Comments
-
ccocker almost 2 years
I am really struggling to understand how to get the current user id of someone logged in and to filter a list by that user id.
I can get the userid easily enough but it doesn't seem to be available at the time of the call to get the customer list.
If someone could assist or point me in the right direction it would be much appreciated.
Authentication Service
import { Injectable } from "@angular/core"; import { AngularFire, AuthProviders, AuthMethods, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2'; import { UserModel } from '../users/models/user.model'; @Injectable() export class AuthenticationService { public displayName: string; public userKey: string; public user: UserModel; constructor(public af: AngularFire) { this.af.auth.subscribe( (auth) => { if (auth != null) { this.user = this.af.database.object('users/' + auth.uid); this.userKey = auth.uid; } }); } logout() { return this.af.auth.logout(); } loginWithEmail(email, password) { return this.af.auth.login({ email: email, password: password, }, { provider: AuthProviders.Password, method: AuthMethods.Password, }); } }
Customer Service
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2'; import { AuthenticationService } from '../authentication/authentication.service'; import { CustomerModel } from './models/customer.model'; @Injectable() export class CustomersService { customersRef: string = '/customers/'; customer: any; usersCustomerId: string; constructor( private af: AngularFire, private authService: AuthenticationService, private router: Router) { } getAllCustomers(): FirebaseListObservable<CustomerModel[]> { this.usersCustomerId = this.authService.userKey; console.log(this.usersCustomerId); return this.af.database.list(this.customersRef, { query: { orderByChild: 'uid', equalTo: this.usersCustomerId } }); } }