Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get AngularFire2 authentication as an observable?

I want to after authenticated set isAuthenticated:boolean to True after successful Federated Google Sign-in, or user is signed in state.

import {Injectable} from '@angular/core';
import {AngularFire} from 'angularfire2';
import {Observable} from 'rxjs/Observable';


//this current code is not making sense. Any suggestion 
//to make it an Observable for Signin and Logout?
@Injectable()
export class AuthService {
  isAuthenticated:boolean = false;
  authObj: Observable<any>;

  constructor(public af:AngularFire) {
    this.authObj = af.auth;
  }

  signin() {
    //I want to make AngularFire2 Authentication token/obj an Observable. So this will keep emitting an Observable
    //that return True.... after successful Federated Google Signin. I want my other component to subscribe to this Observable.
    return this.authObj.do(val => this.af.auth.login());
    this.isAuthenticated = true;
  }

}
like image 244
Jek Avatar asked Jul 09 '16 17:07

Jek


2 Answers

I wrote a piece that takes the bits and pieces and joins them together. You might have to create an Auth Service like this:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
import { Observable } from 'rxjs/Observable';

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFire } from 'angularfire2';

@Injectable()
export class AuthGuard implements CanActivate{
  public allowed: boolean;

  constructor(private af: AngularFire, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.af.auth.map((auth) =>  {
      if(auth == null) {
        this.router.navigate(['/login']);
        return false;
      } else {
        return true;
      }
    }).first()
  }
}

Check the AngularFire2 Authentication article for more info.

like image 123
KhoPhi Avatar answered Oct 21 '22 03:10

KhoPhi


Just subscribe to the auth object to get notified when there is a user object or not...

  var auth = this.af.auth.subscribe( (user) => {
    debugger;
    if (user) {
      // User signed in!
      var uid = user.uid;
      console.log(uid)
    } else {
      // User logged out
      console.log("no user")
    }
  });
like image 30
Aaron Saunders Avatar answered Oct 21 '22 03:10

Aaron Saunders