Angular 角8&;用户登录后Firebase AuthGuard仍在重定向到登录
登录后,我在上遇到问题,链接不起作用,或者我无法访问路由/链接,仍然将我重定向回登录页面。正确的输出应该是,我可以在登录后访问所有链接/路由。我使用firebase作为我的数据库 我的身份验证服务类型脚本Angular 角8&;用户登录后Firebase AuthGuard仍在重定向到登录,angular,firebase,angular7,angular8,angular-router-guards,Angular,Firebase,Angular7,Angular8,Angular Router Guards,登录后,我在上遇到问题,链接不起作用,或者我无法访问路由/链接,仍然将我重定向回登录页面。正确的输出应该是,我可以在登录后访问所有链接/路由。我使用firebase作为我的数据库 我的身份验证服务类型脚本 @Injectable({ providedIn: 'root' }) export class AuthService { user: Observable<firebase.User>; user$: Observable<User>; con
@Injectable({
providedIn: 'root'
})
export class AuthService {
user: Observable<firebase.User>;
user$: Observable<User>;
constructor(
public db: AngularFirestore,
public afAuth: AngularFireAuth,
public router: Router
) { this.user$ = this.afAuth.authState;
}
login(email: string, password: string){
this.afAuth.auth.signInWithEmailAndPassword(email, password).then(
value => {
sessionStorage.setItem("loggedIn", email);
console.log('Success!', value);
this.router.navigate(['dashboard']);
}
).catch(err=>{
console.log('Something went wrong:',err.message);
this.router.navigate(['sign-up']);
})
}
signup(email: string, password: string){
this.afAuth.auth.createUserWithEmailAndPassword(email, password).then(
value => {
console.log('Success!', value);
this.router.navigate(['dashboard']);
}
).catch(err=>{
console.log('Something went wrong:',err.message);
})
}
logout(){
this.afAuth.auth.signOut();
this.router.navigate(['sign-in']);
}
}
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService:AuthService, private router:Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('loggedIn')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/sign-in'], { queryParams: { returnUrl: state.url }});
return false;
}
}
我的路线
const routes: Routes = [
{ path: '', redirectTo: '/sign-in', pathMatch: 'full' },
{ path: 'books', component: BooksComponent, canActivate: [AuthGuard] },
{ path: 'add-book', component: AddBookComponent, canActivate: [AuthGuard] },
{ path: 'sign-in', component: SignInComponent },
{ path: 'sign-up', component: SignUpComponent },
{ path: 'dashboard', component: DashboardComponent }
]
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class SignInComponent implements OnInit {
email: string;
password: string;
constructor(public auth: AuthService) { }
ngOnInit() {
}
login(){
this.auth.login(this.email, this.password);
this.email = this.password = '';
}
}
最后是我的登录组件
const routes: Routes = [
{ path: '', redirectTo: '/sign-in', pathMatch: 'full' },
{ path: 'books', component: BooksComponent, canActivate: [AuthGuard] },
{ path: 'add-book', component: AddBookComponent, canActivate: [AuthGuard] },
{ path: 'sign-in', component: SignInComponent },
{ path: 'sign-up', component: SignUpComponent },
{ path: 'dashboard', component: DashboardComponent }
]
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class SignInComponent implements OnInit {
email: string;
password: string;
constructor(public auth: AuthService) { }
ngOnInit() {
}
login(){
this.auth.login(this.email, this.password);
this.email = this.password = '';
}
}
多谢各位。我的输出应该是,在我登录后,我可以访问所有在登录前已被防护激活的路由如果您混合了
会话存储
和本地存储
,您需要选择其中一个,因为它们不相同。如果在sessionStorage
中设置了某些内容,则在localStorage
中找不到该内容。但我真的不认为你需要它们中的任何一个。您有authState
,您可以在authguard中收听。Angularfire也有内置的路线守卫,所以你也可以考虑使用:但是,如果你想要自己的后卫,我建议如下:
从'rxjs/operators'导入{take,map};
从“firebase”导入{User};
@可注射()
导出类AuthGuard实现了CanActivate{
构造函数(私有authService:authService,私有路由器:路由器){}
canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot){
返回此.authService.user$.pipe(
以(1)为例,
地图((用户:用户)=>{
如果(用户){
返回true;
}
this.router.navigate(['/sign-in'],{queryParams:{returnUrl:state.url}});
返回false;
})
)
}
}
对我有用:
auth.guard.ts:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { map, tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private afAuth: AngularFireAuth, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.afAuth.user.pipe(
tap(user => {
if (!user) {
this.router.navigate([ 'signin' ], { queryParams: { returnUrl: state.url } });
}
}),
map(user => !!user )
);
}
}
“@angular/core”:“~10.1.5”,
“@angular/fire”:“^6.0.3”,我看到您已将项目存储在会话存储中,并验证了项目的值localstorage@SuryaPrakashTumma-好的,先生,我遗漏了什么?我在这里没有做太多的调查,但我知道角度路由器将路由到它匹配的第一条路由。尝试将空路线向下移动。此外,route guard的canActivate方法还可以返回UrlTree。尝试使用它,而不是将路由器注入路由。