繁体   English   中英

Angular2 CanActivate 导航

[英]Angular2 CanActivate Navigate

我有以下问题。 我制作了一个 CanActivate Guard,如果您已登录,您可以“转到”债务组件。 我的问题是当我登录时我想将用户重定向到债务组件(因为 RegistrationComponent 是默认的),但它不起作用(实际上我的页面被阻塞了......而且我不能做任何事情)。 我的 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]}
];

我所做的是一种黑客行为,但它完美无缺:

首先,我确实在我的LoginCompoment路由上设置了一个Guard

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

然后我使用RouterStateSnapshot获取我的 URL 状态的单个实例,指示我用户尝试访问的内容。

然后我可以管理 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上设置了保护,而即使用户未通过身份验证,它仍然允许用户访问它。 仍然运作良好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM