登录后 Angular2 重定向 [英] Angular2 Redirect After Login

查看:25
本文介绍了登录后 Angular2 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 angular2 中创建一个身份验证系统,其想法是如果未通过身份验证的用户尝试导航到受保护"的 url,系统会将用户重定向到登录页面,并在 url 中输入查询参数称为next",这将帮助登录系统将用户重定向回他最初想要访问的位置.

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;
    }
}

此方法不起作用,因为 nextInstrurlPath 属性未显示完整"网址(例如,它缺少查询参数).

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();

让我们根据 routeconfig 说以下结构示例:

Lets say following structure example depending on routeconfig:

login?next=my-redirect-url

然后您使用navigateByUrl 导航到以下网址

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆