【发布时间】: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