Angular2 CanActivate导航

时间:2017-01-12 08:57:55

标签: angular angular2-routing

我有以下问题。我已经建立了一个CanActivate Guard,如果你已经登录,你可以"去"到债务组件。我的问题是当我登录并且我想将用户重定向到债务组件时(因为注册组件是默认的),但是它不起作用(实际上我的页面正在阻塞......而我什么也做不了)。我的CanActivate功能

export class AuthGuardService implements CanActivate {

constructor(private router: Router) { }

canActivate(): Promise<boolean>{
    return checkIfAuth().then(() => {
        setLoggedIn(true);
        this.router.navigate(['/debts']); // <- broken :(
        return true;
    }).catch(() => {
        setLoggedIn(false);
        this.router.navigate(['/login']); // <- broken :(
        return false;
    })
  }
}


export function checkIfAuth () {
return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
        if(user){
            return resolve(true);
        }
        else{
            return reject(false);
        }
    })
  })
}

任何我的app.routing

const APP_ROUTES: Routes = [
    { path: '', redirectTo: '/registration', pathMatch: 'full' },
    {  path: 'registration', component: RegistrationComponent },
    { path: 'login', component: LoginComponent },
    { path: 'myaccount', component: AccountComponent, canActivate: [AuthGuardService]},
    { path: 'debts', component: DebtsComponent, canActivate: [AuthGuardService]}
];

1 个答案:

答案 0 :(得分:4)

我所做的是一种破解,但它完美无缺:

首先,我在Guard路线上设置了LoginCompoment

{ path: 'login', component: LoginComponent, canActivate: [AuthGuard] }

然后我使用RouterStateSnapshot获取我的网址状态的单个实例,告诉我用户试图访问的内容。

然后我可以在Guard中管理案例:

import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

...

/**
 *  Protects the routes to reach with authentication
 */
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    // Set user authentication state depending on the token's existance
    this.authService.setLoggedInState();
    // Check user authentication state
    if (this.authService.isAuthenticated) {
      // Explicit navigation to '/login' while the user is already authenticated
      if (state.url === '/login') {
        this.router.navigate(['/dashboard']); // Debts for you
      }
      return true;
    } else {
      // Allow route to './login' to get authenticated
      if (state.url === '/login') {
        return true;
      }
      // Explicit navigation to any URL while not being authenticated
      this.router.navigate(['/login']);
      return false;
    }
  }

有关快照的文档链接:https://angular.io/docs/ts/latest/guide/router.html#!#sts=Snapshot:%20the%20no-observable%20alternative

为了让它适用于您的情况,您只需要将setLoggedInState()调整到您已经拥有的案例中。

注意:我将此解决方案称为 HACK ,因为您实际上在Login上设置了一个警卫,但即使它仍然允许用户访问它他没有经过身份验证。仍然运作良好。