首页 文章

Angular 2安全性:登录后重定向到点击的路线?

提问于
浏览
1

我当前在2.1.0上'm building my first app using the release version of Angular 2 (I' . 我已经设置了Route Guard,我在我的routing.ts中使用它来保护其中一条带有身份验证的路由 . 单击时,如果未登录,则会将用户重定向到登录路由 . 他们可以登录,如果经过身份验证,则会设置localStorage令牌 . 这里's where I have a problem. I want to then redirect the user to the route they clicked on initially before they were redirected to the login, but I can' t了解如何在点击Guard canActivate方法或登录时获取点击的路线 . 这似乎是一个相当常见的使用场景,但我找不到任何这样做的例子 .

1 回答

  • 1

    好的,这是我剥离的例子,应该说明一点:

    @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([''])
            }
        }
    
    }
    

相关问题