当我不登录时尝试访问URL或重定向页面时,它工作正常,然后当我登录时,我仍然无法访问该页面,并将我重定向到登录页面。建议请谢谢!
Auth.service.ts
//Import complete...
...
...
import { Router } from "@angular/router";
import { Observable, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
user: Observable<firebase.User>;
user$: Observable<User>;
constructor(
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']);
})
}
Auth.guard.ts (已编辑)
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router)
{}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean | UrlTree {
if(this.authService.isLoggedIn){
return true;
}
else{
return this.router.parseUrl("/sign-in");
}
}
}
在App.module.ts中-我添加了提供程序
providers: [BookService, AuthService, AuthGuard],
最后, app-routing.module.ts
//Imports
..
..
..
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 AppRoutingModule { }
答案 0 :(得分:2)
您的逻辑似乎很好,但是!您正在检查名为'currentUser'的本地存储中的值,但没有在AuthService的登录功能中为本地存储中的该键设置任何值。您只是在登录功能中将值设置为'loggedIn'。
在AuthGuard中更改此行
if (localStorage.getItem('currentUser')) {
到
if (localStorage.getItem('loggedIn')) {
将解决此错误。
编辑:-您正在将AuthService中的登录值设置为sessionStorage,而在AuthGuard中,您正在从localStorage检查该值。是什么原因呢?