Angular 角度2+;firebase应用程序在刷新时让用户注销

Angular 角度2+;firebase应用程序在刷新时让用户注销,angular,authentication,firebase,firebase-authentication,angular-services,Angular,Authentication,Firebase,Firebase Authentication,Angular Services,我对Angular2、Firebase、SPAs等都是陌生的。这些天我有一个任务,就是给Angular2(使用Firebase email&pw auth)应用程序添加一些新功能。该应用程序主要由一个博客(主页)、一个商店(/shop)和一个管理区(/admin)表单组成,您可以管理博客帖子和商店项目。该任务的一个要求是,如果您在浏览器上点击“刷新”,应用程序将保持会话,这样,如果您在/admin区域的任何“页面”上,您将不会被带回登录表单,而当前正在发生这种情况。我真的花了几个小时在网上寻找解

我对Angular2、Firebase、SPAs等都是陌生的。这些天我有一个任务,就是给Angular2(使用Firebase email&pw auth)应用程序添加一些新功能。该应用程序主要由一个博客(主页)、一个商店(/shop)和一个管理区(/admin)表单组成,您可以管理博客帖子和商店项目。该任务的一个要求是,如果您在浏览器上点击“刷新”,应用程序将保持会话,这样,如果您在/admin区域的任何“页面”上,您将不会被带回登录表单,而当前正在发生这种情况。我真的花了几个小时在网上寻找解决方案,但没能找到。我试图保存一个localstorage令牌,但发现firebase已经保存了该令牌,以及其他许多东西,但仍然找不到解决方案。应用程序已经有了一个检查登录用户的机制和一个路由保护,用于管理区域中的管理博客(/admin/bog admin)和管理产品(/admin/product admin)部分。我将尝试发布我认为与此问题相关的内容,如果我忘记了任何内容,请随时索取更多代码片段。另外,请简要说明您的解决方案,因为我也确实需要了解它。
user.service.ts:

从'@angular/core'导入{Injectable};
进口{
激活,
路由器,
激活的路由快照,
路由器状态快照
}来自“@angular/router”;
从“firebase”导入*作为firebase;
从“ng2 toastr/ng2 toastr”导入{toastmanager};
@可注射()
导出类UserService实现了CanActivate{
userLoggedIn:boolean=false;
loggedInUser:字符串;
authUser:any;
构造函数(专用路由器:路由器,公用toastr:ToAstManager){
firebase.initializeApp({
apiKey:“AIzaSyB7VgN55gflpKAlmM41r2DCdUsy69JkLsk”,
authDomain:“angulargigabyte-966ef.firebaseapp.com”,
数据库URL:“https://angulargigabyte-966ef.firebaseio.com",
projectId:“angulargigabyte-966ef”,
storageBucket:“angulargigabyte-966ef.appspot.com”,
messagingSenderId:“154241614671”
})
}
canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot):布尔值{
让url:string=state.url;
返回此.verifyLogin(url);
}
verifyLogin(url:string):布尔值{
if(this.userLoggedIn){
返回true;
}
this.router.navigate(['/admin/login']);
返回false;
}
注册(电子邮件:字符串,密码:字符串){
firebase.auth().createUserWithEmailAndPassword(电子邮件,密码)
.catch(函数(错误){
警报(`${error.message}请重试!`);
});
}
verifyUser(){
this.authUser=firebase.auth().currentUser;
if(this.authUser){
this.toastr.success('Alert','Welcome${this.authUser.email}');
this.loggedInUser=this.authUser.email;
this.userLoggedIn=true;
this.router.navigate(['/admin']);
}
}
登录(LoginMail:string,loginPassword:string){
firebase.auth().signInWithEmailAndPassword(LoginMail,loginPassword)
.catch(函数(错误){
警报(`${error.message}无法登录。请重试!`);
});
}
注销(){
this.userLoggedIn=false;
firebase.auth().signOut().then(函数(){
},函数(错误){
警报(`${error.message}无法注销。请重试!`);
});
}
}

login.component.ts


为什么不使用angularfire2?()

您可以使用可观察的authState,如:

afAuth.authState.subscribe((resp) => {
  if (resp.uid){
    //user is already logged
  }
});

更多信息请访问

谢谢您的回答。我担心除了我已经在应用程序中使用的框架之外,我可能不被允许使用其他框架。
afAuth.authState.subscribe((resp) => {
  if (resp.uid){
    //user is already logged
  }
});