Rerouting angular 5 app with AngularFireAuth

有些话、适合烂在心里 提交于 2019-12-11 08:37:19

问题


I got the simple authentication working with AngularFireAuth but now my routing doesn't work anymore the console.logs show that the 'test' comes before 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){
    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!');
    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);
}
}

login component

constructor(private router: Router, private service: AuthService){}
loginUser() {
    this.service.login(this.email, this.password).subscribe(userIsLoggedIn =>
      this.router.navigate(['admin/overview']));
      this.email = this.password = '';
      console.log('test');
  }

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

来源:https://stackoverflow.com/questions/49562303/rerouting-angular-5-app-with-angularfireauth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!