不能保护用户表单访问angular的登录页面



我想阻止用户访问登录页面,如果已经登录。我使用的是带有Firebase认证的Angular。

我成功地通过写一个auth.guard.ts来阻止用户访问应用程序像这样:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { map, tap} from 'rxjs/operators';
import { AuthentificationService } from '../services/authentification.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {

constructor(
private authService: AuthentificationService,
private router: Router
) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.user$
.pipe(map(authState => !!authState))
.pipe(tap(auth => !auth ? this.router.navigate(['sign-in']) : true))
}
}

然后注入到我的app.routing.ts它工作得很好:

const routes: Routes = [
{ 
path: '', 
redirectTo: '/sign-in',
pathMatch: 'full',
},
{ 
path: 'sign-in', 
component: SignInComponent,
//canActivate: [AnonymousGuard]
},
{ 
path: 'scanner', 
component: ScannerComponent,
canActivate: [AuthGuard],
},
{ 
path: 'view-entries', 
component: ViewEntriesComponent,
canActivate: [AuthGuard],
},
{ 
path: '**', 
redirectTo: ''
}
];
然后,我告诉自己,为了保护登录页面,我只需要写一个anonymous.guard.ts以几乎相同的方式注入。
export class AnonymousGuard implements CanActivate {
constructor(    
private authService: AuthentificationService,
private router: Router) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.user$
.pipe(map(authState => !!authState))
.pipe(tap(auth => !!auth))
.pipe(tap(auth => auth ? this.router.navigate(['scanner']) : true))
}

}

但是通过这样做,当我退出/当我不登录时,我的应用程序卡住了。我不明白为什么……我做错了什么?

[EDIT]我的服务只是保持可观察对象,使其在应用程序中可以访问,像这样:

user$: Observable<any>;
constructor(
private angularFireAuth: AngularFireAuth,
private router: Router
) {
this.user$ = this.angularFireAuth.authState;
} 

你可以将' Route Guards '应用到web应用的认证区域,或者需要特殊权限才能访问的管理部分。

最新更新