Angular 5 登录后重定向到之前的页面。
当我手动输入URL时,如果未登录,它会重定向到登录页面,但登录后,应该重定向到输入的URL,但现在我只能使用以下方式重定向到主页:
this.router.navigate(['/homepage']);
有一些想法吗?
Angular 5 登录后重定向到之前的页面。
当我手动输入URL时,如果未登录,它会重定向到登录页面,但登录后,应该重定向到输入的URL,但现在我只能使用以下方式重定向到主页:
this.router.navigate(['/homepage']);
有一些想法吗?
当你使用守卫重定向到登录页面时,可以将源URL放在 queryParams
中,如下所示:
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;
}
}
登录后,您可以从查询参数中获取原始页面网址:
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'])
}
@Component({ ... })
class SomePageComponent {
constructor(private route: ActivatedRoute, private router: Router) {}
checkLogin() {
if (!this.auth.loggedIn()) {
this.router.navigate(['/homepage`], { queryParams: { redirectTo: this.route.snapshot.url } });
}
}
}
@Component({...})
class LoginComponent {
constructor(private router: Router, private route: ActivatedRoute) {}
backToPreviousPage() {
this.router.navigate(
[this.route.snapshot.queryParams.get('redirectTo')]
);
}
}
@Component({ ... })
class SomePageComponent {
constructor(private router: Router) {}
checkLogin() {
if (!this.auth.loggedIn()) {
this.router.navigate(['login'], { state: { redirect: this.router.url } });
}
}
}
@Component({...})
class LoginComponent {
constructor(private router: Router) {}
backToPreviousPage() {
const { redirect } = window.history.state;
this.router.navigateByUrl(redirect || '/homepage');
}
}
对我来说,查询参数并不起作用,因为如果用户去登录,然后进入注册路由,所以您需要保留查询参数。但是,如果在登录之前有更多步骤,或者用户刷新页面,或者地铁上的互联网不好或发生其他事情导致他失去了参数,那么他将被重定向到谁知道哪里……但是,如果您将所需的URL设置为重定向到localStorage,并且在登录/注册/其他步骤之后,您可以将其重定向到以前从localStorage中删除字符串所需的URL。
// needed page
localStorage.setItem('redirectTo', this.router.url);
this.router.navigateByUrl('/login');
// login/signup/else step page
success => {
const redirect = localStorage.getItem('redirectTo');
if (redirect) {
localStorage.removeItem('redirectTo');
this.router.navigate(redirect);
} else {
this.router.navigate('defaultpath');
}
}
在authService url: string
中声明变量,并在您的auth.gaurd.ts
中使用该变量。
this.authService.redirectUrl = url;
this.navigateTo("/login");
return false;
接下来在 login.ts
文件中编写代码。
if (this.authService`enter code here`.redirectUrl) {
this.router.navigateByUrl(this.authService.redirectUrl);
} else {
this.router.navigateByUrl("/home");
}
subscribe
部分中,对吗? - Barefaced Bear