2

I got the simple authentication working with AngularFireAuth but now my routing doesn't work anymore the console.logs shows the 'Nice it worked', so what is wrong? (this is mainly just the routing guard out of the documentation)

auth-service

@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);
}
}

routing

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

auth-guard

@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;
}
Burst of Ice
  • 386
  • 2
  • 6
  • 23

1 Answers1

0

i think that you have to set this.isLoggedIn to true before route navigation, your guard is refusing navigation because isLoggedIn is still false:

.then(value => {
  console.log('Nice, it worked!');
 // set this.isLoggedIn to true here
 this.router.navigate(['admin/overview'])
});
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52