我有一个受保护的路由/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
都返回空值。
在 AuthenticatedRouteGuardService 中使用它
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authenticationService.isAuthenticated()) {
return true;
}
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}