2

我使用 AngularFireAuth 进行了简单的身份验证,但现在我的路由不再起作用了,console.logs 显示“很好用”,那么出了什么问题?(这主要只是文档中的路由保护

认证服务

@Injectable()
export class AuthService {
  user: Observable<firebase.User>;
  constructor(private firebaseAuth: AngularFireAuth, private router: Router){
    this.user = firebaseAuth.authState;
  }
  isLoggedIn = false;

  login(email: string, password: string): Observable<boolean> {
    this.firebaseAuth
  .auth
  .signInWithEmailAndPassword(email, password)
  .then(value => {
    console.log('Nice, it worked!');
this.router.navigate(['admin/overview']));
    return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
  })
  .catch(err => {
    console.log('Something went wrong:',err.message);
  });
return Observable.of(false).delay(1000).do(val => this.isLoggedIn = false);
}
}

路由

{
  path: 'admin',
  component: AdminLoginComponent,
  data: {title: 'Admin'}
},
{
  path: 'admin/overview',
  component: AdminOverviewComponent,
  canActivate: [AuthGuard],
  data: {title: 'Overview'}
}

授权保护

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
 let url: string = state.url;

 return this.checkLogin(url);
}

canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
 return this.canActivate(route, state);
}

checkLogin(url: string): boolean {
 if (this.authService.isLoggedIn) { return true; }

 // Store the attempted URL for redirecting
 this.authService.redirectUrl = url;

 // Navigate to the login page with extras
 this.router.navigate(['/admin']);
 return false;
}
4

1 回答 1

0

我认为您必须在路线导航之前将 this.isLoggedIn 设置为 true,您的警卫拒绝导航,因为 isLoggedIn 仍然为 false:

.then(value => {
  console.log('Nice, it worked!');
 // set this.isLoggedIn to true here
 this.router.navigate(['admin/overview'])
});
于 2018-03-30T15:04:04.023 回答