我实际上正在学习 Angular 和 firebase,我想在用户仪表板中添加一个路由保护,这样只有登录的用户才能查看该页面。身份验证工作正常,但我在限制没有登录用户访问用户仪表板时遇到问题这是我下面的代码。
验证服务.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthServiceService {
newUser: any;
// passing Error message
private eventAuthError = new BehaviorSubject<string>('');
eventError$ = this.eventAuthError.asObservable();
showSuccessCreated: boolean;
constructor( private authz: AngularFireAuth, private db: AngularFirestore, private route:Router)
{ }
// geting user details
getUserState() {
return this.authz.authState;
}
// LoggIn Users
login(email: string , password: string ) {
this.authz.auth.signInWithEmailAndPassword(email, password)
.catch( error => {
this.eventAuthError.next(error);
}).then(userCredential => {
if (userCredential) {
this.route.navigate(['/dashboard']);
}
});
}
这是 Authguard 服务,我尝试从我的 authservice.service.ts 中引用登录方法,但尽管我没有登录,但它仍然重定向到用户的仪表板。
authguard.service.ts
export class AuthguardService implements CanActivate {
constructor(private authservice: AuthServiceService, private route: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let isAuthenicated = !!this.authservice.login;
if(isAuthenicated ){
return true;
}
console.log('Access denied');
this.route.navigate(['/login']);
return false;
}
}
路由.module.ts
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate:[AuthguardService],
children: [
{path: '', redirectTo: 'employees', pathMatch: 'full'},
{path: 'employees', component: EmployeelistComponent, resolve: {employeeList: ResolverGuardService}},
{path: 'detail/:id', component: EmployeeDetailComponent, canActivate: [CanActivateGuardService],
{ path: 'notfound', component: PageNotFoundComponent},
]
},
];