我对角度和设计小型网络应用程序的过程非常陌生 .
我使用angularfire2创建了一个简单的电子邮件/密码登录 . 验证部分工作正常 . 但是,看起来某些原因的authguard始终认为用户已注销,即使我创建的auth服务中的console.log返回用户 .
这是我的实现:
Service:
export class AuthService {
private user: Observable<firebase.User> = null;
private userDetails: firebase.User = null;
constructor(public firebaseAuth: AngularFireAuth, private router: Router) {
this.user = firebaseAuth.authState;
this.user.subscribe(
(user) => {
if (user) {
this.userDetails = user;
console.log(this.userDetails.uid);
console.log('service: logged');
} else {
this.userDetails = null;
console.log('service: logged out');
}
}
);
}
isAuthenticated() {
if (this.userDetails == null ) {
return false;
} else {
return true;
}
}
}
我使用 isAuthenticated() 函数(在AuthGuard中)来确定用户是否已登录 .
Auth Guard:
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {}
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isAuthenticated()) {
console.log('guard: user is logged in ')
return true;
} else {
this.router.navigate(['login']);
console.log('guard: user is not logged in ')
return false;
}
}
}
我的问题是,为什么AuthGuard中使用的函数认为用户没有登录,但AuthService认为用户已登录?此外,我注意到页面刷新时,用户注销 . 有没有办法解决这两个问题?
非常感谢您的宝贵时间 .
编辑:
Routes Array
const appRoutes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full',
},
{ path: '', component: FullLayoutComponent, data: { title: 'home' }, children: HOME_ROUTES, canActivate: [AuthGuard] }, // 'home page' is here
{ path: '', component: ContentLayoutComponent, data: { title: 'content' }, children: CONTENT_ROUTES}, // login page is a child here
];
登录页面定义为CONTENT_ROUTES中的子项,其中默认路由为HOME_ROUTES .