Angular 2安全性:登录后重定向到点击路线?
问题描述:
我正在使用Angular 2的发布版构建我的第一个应用程序(目前我在2.1.0上)。我建立了一个Route Guard,我在我的routing.ts中使用它来保护其中一个具有认证的路由。点击后,如果未登录,它会将用户重定向到登录路线。在那里他们可以登录,如果通过身份验证,它会设置一个localStorage标记。这是我遇到问题的地方。然后,我想在重定向到登录前将用户重定向到它们最初点击的路线,但我无法弄清楚如何在点击Guard canActivate方法或登录时获取点击路线。这似乎是一个相当常见的使用场景,但我找不到任何这样做的例子。Angular 2安全性:登录后重定向到点击路线?
答
好吧,这是我剥离出来例子应该说明这一点:
@Injectable()
export class AuthGuardService implements CanActivate
{
toUrl;
constructor(public authenticationService: AuthenticationService,
public router: Router)
{
}
canActivate(route, state): boolean
{
this.toUrl = state.url; //This is the url where its going
if (this.authenticationService.isLoggedIn()) return true;
this.router.navigate(['/login', {redirect: this.toUrl}]);
}
}
,并在登录组件使用ngOnInit来检查任何重定向ulrs:
export class LoginComponent
{
redirect;
constructor(
private authenticationService: AuthenticationService,
private route: ActivatedRoute,
private router: Router)
{
}
ngOnInit()
{
this.redirect = this.route.snapshot.params['redirect'];
}
logIn(): void
{
this.authenticationService
.login(this.searchParams)
.subscribe(
() =>
{
this.logInSuccess();
},
error =>
{
this.logInFail(error)
})
}
logInSuccess(): void
{
if (this.redirect)
{
this.router.navigateByUrl(this.redirect);
}
else
{
this.router.navigate([''])
}
}
}
所以这样的路线警卫的作品是,它击中了警卫的canActivate方法,以确定用户是否已经过身份验证。在这种方法中,我试图抓取this.router.url,但它等于用户点击安全路线链接时的路线,而不是新路线。地址栏中的URL是当前路由,而不是新的安全路由。所以我无法知道用户点击了哪个安全路线。或者至少我不认为我会这样做,我希望有人能告诉我如何获得新的路线,以便我可以完全按照您的建议进行操作。 – Eddie
我在我的应用程序中实现这一点意味着要做一段时间。我分享我是如何做到的。 –
我明白你的意思了,我一直在努力寻找新路线。似乎无法在任何地方找到它。 –