【问题标题】:Angular / Firebase Authentication - Make boolean Observable from service to component?Angular / Firebase Authentication - 使从服务到组件的布尔可观察?
【发布时间】:2018-07-13 11:27:42
【问题描述】:

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

因此,当存在经过身份验证的用户,并且 'isAuthenticated' 的布尔值为 true 时,应显示元素。

目前,布尔值默认设置为 false,并在成功登录时定义的同一 auth.service 文件中更新,但我也需要在 app.component.ts 文件中更新该值,但不能t 这样做是因为 'Observable' 不能分配给布尔值。

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);
        });    
}

}

can-activate-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>

【问题讨论】:

    标签: angular firebase authentication firebase-authentication


    【解决方案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) { }
    }
    

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

    【讨论】:

    • 谢谢,但这不起作用。这个函数是否打算进入用户登录的组件内部?
    • 我对代码进行了扩展,以便更清楚地说明需要更改的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2018-02-23
    • 2017-11-16
    • 2019-05-25
    • 1970-01-01
    • 2018-01-02
    相关资源
    最近更新 更多