Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Firebase Get Current User

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
      }
    });
  }
}
like image 276
ccocker Avatar asked Nov 29 '22 22:11

ccocker


2 Answers

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>
like image 148
Aamer Shahzad Avatar answered Dec 04 '22 12:12

Aamer Shahzad


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;
}
like image 36
sugarme Avatar answered Dec 04 '22 13:12

sugarme