登录后Angular2重定向 [英] Angular2 Redirect After Login
问题描述
我正在用angular2创建一个身份验证系统,其想法是,如果未经身份验证的用户尝试导航到受保护的" URL,则系统会将用户重定向到登录页面,并在该URL中添加查询参数称为下一个",这将帮助登录系统将用户重定向回他想要的位置.
I'm creating an authentication system in angular2 with the idea that if a user that is not authenticated tries to navigated to a "protected" url, the system will redirect the user to the login page putting in the url a query param called "next" that will help the login system redirect the user back to where he wanted to be in the first place.
login?next=my-redirect-url
为了保护我的组件,我在所有组件中都使用了装饰器@CanActivate(isUserAuthenticated)
. isUserAuthenticated
函数如下:
To protect my components, I'm using the decorator @CanActivate(isUserAuthenticated)
in all of them. The isUserAuthenticated
function is something as follows:
function isUserAuthenticated(
prevInstr: ComponentInstruction,
nextInstr: ComponentInstruction
): boolean {
const authService = injector.get(AuthService);
const router = injector.get(Router);
if(authService.isLoggedIn()) {
return true;
} else {
router.navigate(["/Login", {next: nextInstr.urlPath}]);
return false;
}
}
此方法不起作用,因为nextInstr
的urlPath
属性未显示完整"网址(例如,缺少查询参数).
This approach is not working because the urlPath
property of the nextInstr
is not showing the "complete" url (it lacks query params for example).
是否有一种方法可以从ComponentInstruction
实例(如nextInstr
)构建完整的url?
Is there a way to build the complete url from a ComponentInstruction
instance like nextInstr
?
推荐答案
是的,有一种方法:
let url = router.generate(['./Login', {next: nextInstr.urlPath}]).toRootUrl();
让我们根据路由配置说出以下结构示例:
Lets say following structure example depending on routeconfig:
login?next=my-redirect-url
然后您使用NavigationByUrl导航到以下网址
And then you use navigateByUrl to navigate to following url
router.navigateByUrl('/' + url);
我已经用示例对它进行了测试,结果可以在图像上看到:
I have tested it with my example and result you can see on image:
let instruction = router.generate(['./Country', {country: 'de', a: 1, b: 2}]);
console.log(instruction, instruction.toRootUrl());
这篇关于登录后Angular2重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!