Angular / Firebase身份验证 - 将boolean Observable从服务变为组件?

时间:2018-02-02 22:07:01

标签: angular firebase authentication firebase-authentication

我尝试根据' isAuthenticated'更改[hidden]文件中某些元素的app.component.html属性。组件控制器中存在的布尔值,它与我的auth.service服务中定义的同名属性相匹配。

因此,当有一个经过身份验证的用户时,'的布尔值是经过身份验证的'是的,元素应该显示。

目前,布尔值默认设置为false,并在成功登录时定义的同一auth.service文件中更新,但我需要在app.component.ts文件中更新值但是由于“可观察的”而无法做到这一点。不能转让给布尔人。

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';

@Injectable()

export class AuthService {

private user: Observable<firebase.User>;

isAuthenticated: boolean = false;

  constructor(private firebaseAuth: AngularFireAuth, private router: Router) {
      this.user = firebaseAuth.authState;
  }

signIn(email: string, password: string) {
    this.firebaseAuth
        .auth
        .signInWithEmailAndPassword(email, password)
        .then(value => {
            console.log('Signed In');
            this.isAuthenticated = true;
            this.router.navigateByUrl('/dashboard');
        })
        .catch(err => {
            console.log('Sign-In Error: ', err.message);
        });
}

signOut() {
    this.firebaseAuth
        .auth
        .signOut();
    this.isAuthenticated = false;
    this.router.navigateByUrl('/login');
    console.log('Signed Out');
}

register(email: string, password: string) {
    this.firebaseAuth
        .auth
        .createUserWithEmailAndPassword(email, password)
        .then(value => {
            console.log('Registration Successful', value);
         })
         .catch(err => {
            console.log('Registration Error: ', err.message);
        });    
}

}

可以激活-route.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { AuthService } from './services/auth.service';

@Injectable()

export class CanActivateRouteGuard implements CanActivate {

constructor(private auth: AuthService) { }

canActivate (
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.auth.isAuthenticated;
}

}

app.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { AngularFirestore } from 'angularfire2/firestore';

import { UsersService } from './services/users.service';
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {

isAuthenticated: boolean;
titles: any[];

constructor(public db: AngularFirestore, private usersService: UsersService, public authService: AuthService, private router: Router) {
    this.isAuthenticated = this.authService.isAuthenticated;
}

app.component.html

<button mat-button (click)="signOut()" [hidden]="isAuthenticated">Sign Out</button>

1 个答案:

答案 0 :(得分:1)

尝试从此处更改您的组件(app.component.ts):

isAuthenticated: boolean;

对此:

export class AppComponent {

   get isAuthenticated(): boolean {
       return this.authService.isAuthenticated;
   }

   titles: any[];

   constructor(public db: AngularFirestore, 
               private usersService: UsersService, 
               public authService: AuthService, 
               private router: Router) { }
}

这将确保随着服务值的变化,组件属性将始终获得最新值。