angular 5-登录后重定向上一页 [英] angular 5 - redirect the previous page after sign in

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

问题描述

Angular 5登录后重定向到上一页.

Angular 5 redirect to previous page after sign in.

当我手动输入网址时,如果未登录,它将重定向到登录页面,但登录后,它应该重定向到输入的URL,但是现在我可以使用以下方法重定向到主页:

When I am hitting a url manually, if it is not logged in, it will redirect to login page but after login, it should redirect to url which entered but now I just can redirect to homepage by using this:

this.router.navigate(['/homepage']);

有什么想法吗?

推荐答案

当您使用守护程序重定向到登录页面时,可以将源URL放置在 queryParams 中,如下所示:

When you redirect to the login page with a guard, you could put the source url in the queryParams as such:

canActivate(next: ActivatedRouteSnapshot,
            state: RouterStateSnapshot) {
    if (this.authService.isAuthenticated()) {
        return true;
    } else {
        console.log('Could not authenticate');
        this.router.navigate(['login'],{queryParams:{'redirectURL':state.url}});
        return false;
    }
}

登录后,您可以从查询参数中获取原始页面的网址:

After you log in you can get the original page url from the query params:

let params = this.route.snapshot.queryParams;
    if (params['redirectURL']) {
        this.redirectURL = params['redirectURL'];
    }

...

if (this.redirectURL) {        
    this.router.navigateByUrl(this.redirectURL,)
        .catch(() => this.router.navigate(['homepage']))
} else {

    this.router.navigate(['homepage'])
}

这篇关于angular 5-登录后重定向上一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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