Angular2 Firebase Get Current User
Asked Answered
A

5

6

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
      }
    });
  }
}
Arras answered 6/2, 2017 at 17:4 Comment(0)
C
14

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>
Charette answered 2/12, 2019 at 21:30 Comment(0)
G
6

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;
}
Gautier answered 10/2, 2017 at 15:35 Comment(0)
L
2

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.

Lalapalooza answered 9/6, 2020 at 8:5 Comment(0)
V
0

u can use .subscribe() method in order to retrieve the data u want,here's an exemple :

this.authserve.auth.subscribe(user=>{
  if(user)
    this.curruser = user.email;
})

PS:

  1. authserve is an AngularFireAuth instence
  2. auth is an Observable created inside the authserve
  3. curruser is just a simple string variable
Valleau answered 29/12, 2017 at 15:30 Comment(0)
C
0

Documentation

import { Auth, User } from '@angular/fire/auth';

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

    constructor(
        private auth: Auth,
    ) { }

    async getCurrentUser(): Promise<User | undefined> {
        return await this.auth.currentUser;
    }
}
Cambyses answered 12/7, 2022 at 18:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.