Angular2:触发当前路径保护 - 处理注销操作

mrh*_*mrh 6 angular2-routing angular

我正在使用JWT对用户进行身份验证.我的angular2应用程序中的部分路径受CanActivate Guard保护,如果用户未登录,它将重定向到登录页面.现在我正在实现注销按钮,并希望重定向到登录页面.我想仅在非登录用户(例如帐户页面)看不到当前路由时才重定向.如果用户在例如主页中,我不想重定向到登录页面.

如果我能够检查当前路线是否有防守并且如果存在则触发该防护,那将是完美的.有可能这样做吗?

守护:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.loginService.getCurrentUserName()) {
        // logged in so return true
        return true;
    }
    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
}
Run Code Online (Sandbox Code Playgroud)

小智 2

对于所有需要路由保护的页面,您可以有一个特定的路由路径(如“/account/..”),并且您可以检查路由保护页面是否已登录

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.checkRouteNaviation(this.route.url);
}

public checkRouteNaviation(url) {
    if(url.includes('account') && !this.loginService.getCurrentUserName()) {
        // when url is of guard url and not logged in, redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你