代码之家  ›  专栏  ›  技术社区  ›  Burst of Ice

成功身份验证后角度路由不工作

  •  2
  • Burst of Ice  · 技术社区  · 6 年前

    我使用AngularFireAuth进行了简单的身份验证,但现在我的路由在控制台上不再工作了。日志显示“它工作得很好”,那么怎么了?(这主要是 routing guard 超出文档)

    身份验证服务

    @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;
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Fateh Mohamed    5 年前

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

    .then(value => {
      console.log('Nice, it worked!');
     // set this.isLoggedIn to true here
     this.router.navigate(['admin/overview'])
    });