我有一条受保护的路线/protected-route
。 authentication-guard.service.ts
文件指示如果找不到有效会话,则必须将用户抛向/login
:
/* --- Angular --- */
import { Injectable } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot } from '@angular/router';
/* --- Services --- */
import { AuthenticationService } from './authentication.service';
import { StorageService } from './storage.service';
@Injectable()
export class AuthenticatedRouteGuardService implements CanActivate {
constructor(private authenticationService: AuthenticationService, private
router: Router, private routerStateSnapshot: RouterStateSnapshot) { }
canActivate() {
if (this.authenticationService.isAuthenticated()) { return true; } else {
console.log(this.routerStateSnapshot.url);
this.router.navigate(['/login']);
return false;
}
}
}
我想保存尝试的路由,即/protected-route
能够在成功登录后重定向用户。在用户被投掷到/login
之前,我无法获取路线信息。 router.url
和activatedRoute.snapshot.url
都返回空值。
答案 0 :(得分:1)
在AuthenticatedRouteGuardService
中使用此功能canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authenticationService.isAuthenticated()) {
return true;
}
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}