我已经为我的Angular 2应用程序构建了身份验证。我已经通过使用Firebase身份验证服务实现了这一点。在重新加载页面时,用户注销,但令牌仍然存在于localStorage中。
这是我的代码:
export class AdminService {
email;
password;
error;
invalidLogin;
isLoggedIn = false;
constructor(private af: AngularFireAuth,private router: Router,private route: ActivatedRoute) {
}
login(){
this.af.auth.signInWithEmailAndPassword(this.email,this.password)
.then(authState => {
if(authState){
let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');
this.router.navigate([returnUrl||'/']);
this.isLoggedIn = true;
}
else this.invalidLogin = true;
})
}
logout(){
this.af.auth.signOut();
this.isLoggedIn = false;
this.router.navigate(['/'])
}
}
2条答案
按热度按时间ikfrs5lh1#
用户实际上不会注销。当您重新加载页面时,Firebase客户端将检测本地存储中的信息并再次登录用户。您的代码无法检测到这一点,因此无法正确地路由用户。
在常规的Firebase JavaScript客户端中,您可以通过监听
onAuthStateChanged()
事件来解决这个问题:在AngularFire2中,有一个
FirebaseIdTokenObservable
,它暴露了一个Observable<firebase.User>
。它似乎也是这么做的,虽然我承认我从来没有用过它。kiayqfof2#
如果你想使用async函数,你也可以这样做
现在你可以用在警卫身上了