Angular + Firebase -组件在页面刷新时不保持认证状态



你好,我正在尝试使用Firebase为我的Angular应用程序构建简单的身份验证服务。问题是-用户可以登录/注册,我能够在本地存储中保存他的凭据。但是,当我刷新页面时,本地存储中的信息仍然存在,但是我的组件显示的视图应该是为未登录的用户提供的(因此我的身份验证状态等于注销)。如果我不刷新页面,一切工作的方式应该是。下面是我的Auth服务(Auth . Service .ts):

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { BehaviorSubject } from 'rxjs';
import { Router } from '@angular/router';
interface User{
name: string;
email: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
signedin$ = new BehaviorSubject(false)
userData
constructor(public firebaseAuth: AngularFireAuth, private router: Router) {
this.firebaseAuth.authState.subscribe((user)=>{
if(user){
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
}else{
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
})
}
signup(email: string, password: string) {
this.firebaseAuth
.createUserWithEmailAndPassword(email, password)
.then(value => {
this.router.navigate(['auth/login'])
console.log('Success!', value);
})
.catch(err => {
console.log('Something went wrong:',err.message);
});
}
login(email: string, password: string) {
return this.firebaseAuth
.signInWithEmailAndPassword(email, password)
.then((result) => {
this.signedin$.next(true)
console.log('Nice, it worked!', result);
return result
})
.catch(err => {
console.log('Something went wrong:',err.message);
});
}
logout() {
return this.firebaseAuth.signOut().then(() => {
this.signedin$.next(false)
localStorage.removeItem('user');
this.router.navigate(['movies']);
})
}
}

这是我的App.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth2/auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
signedin;
constructor(private authService: AuthService) { }
ngOnInit() {
this.authService.signedin$
.subscribe((data) => {
console.log(data)
this.signedin = data
})
}
logOut() {
this.authService.logout()
this.authService.signedin$
.subscribe((signedInData) => {
this.signedin = signedInData
})
}
}

在核心/应用程序/主组件我想检查的用户统计-登录/注销。我订阅了Auth服务中的行为主体。我试过不同的方法,但都不奏效。我希望有解决办法。我还没有实施任何Auth卫兵。是这个问题导致我的组件视图崩溃每当我刷新页面?提前感谢!

谢谢你用这么简洁的方式提问。

你代码中的问题是当你刷新时,你定义的行为主体不会保存它的状态,因为服务类也会从头开始。

您必须检查本地存储以知道用户是否已登录,因为只有loggedIn用户信息将存在。

在auth.service中创建方法

isUserSignedIn(){
if(localstorage.getItem('user')){ return true;
}
else return false;
}

现在在组件this.authService.isUserSignedIn()

如果你想要整个用户信息,从函数返回,而不是布尔值true/false。

return localstorage.getItem('user')