首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2 CanActivate导航

Angular2 CanActivate导航
EN

Stack Overflow用户
提问于 2017-01-12 08:57:55
回答 1查看 6.2K关注 0票数 4

我有跟踪问题。我已经做了一个CanActivate警卫,如果你登录,你可以“去”债务组件。我的问题是,当我登录,我想重定向用户到债务组件(因为RegistrationComponent是默认的),但它不工作(实际上我的页面阻塞。我什么也做不了)。我的CanActivate函数

代码语言:javascript
复制
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

代码语言:javascript
复制
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]}
];
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-12 10:07:34

我所做的是一次黑客攻击,但效果完美无缺:

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

代码语言:javascript
复制
{ path: 'login', component: LoginComponent, canActivate: [AuthGuard] }

然后,我使用RouterStateSnapshot获取状态的单个实例,指示用户试图达到的目标。

然后,我可以管理警卫的案件:

代码语言:javascript
复制
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()以适应您的情况,这似乎您已经有了。

N.B :,我把这个解决方案称为HACK,因为您实际上设置了一个Login的守卫,而它仍然允许用户访问它,即使他没有经过身份验证。还是很管用的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41608830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档