我一直在尝试在我的 web 应用程序中正确实现 AuthGuard。目前,当我在应用程序中导航时,它工作正常。但是当我刷新时, authService.loggedIn 在 AuthService 完成执行之前被处理为 false 。
这是我的代码:
auth.guard.ts
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Injectable} from '@angular/core';
import {AuthService} from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (state.url === '/login') {
if (this.authService.loggedIn) {
this.router.navigate(['/']).then().catch();
} else {
return true;
}
} else {
if (this.authService.loggedIn) {
return true;
} else {
this.router.navigate(['/login']).then().catch();
}
}
}
}
身份验证服务
import {Injectable, OnInit} from '@angular/core';
import {AngularFireAuth} from '@angular/fire/auth';
import {auth} from 'firebase';
import {Router} from '@angular/router';
import {Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService implements OnInit {
loggedIn = false;
constructor(public afAuth: AngularFireAuth, private router: Router) {
this.afAuth.authState.subscribe((user) => {
if (user) {
this.loggedIn = true;
}
});
}
ngOnInit() {
}
...
}
我在网上研究,他们提到了不同的方法(例如https://gist.github.com/codediodeio/3e28887e5d1ab50755a32c1540cfd121),但无法使其在我的应用程序上运行。
当我尝试这种方法时遇到的一个错误是“src/app/auth.guard.ts(20,8) 中的错误:错误 TS2339:属性 'take' 在类型 'Observable' 上不存在。” 我用
import {AngularFireAuth} from '@angular/fire/auth';
并不是
import { AngularFireAuth } from 'angularfire2/auth';
任何帮助/建议表示赞赏。
感谢大家。