在Angular 4中保存重定向URL以进行授权保护拒绝

时间:2017-04-09 05:52:32

标签: angular routing

我有一条受保护的路线/protected-routeauthentication-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.urlactivatedRoute.snapshot.url都返回空值。

1 个答案:

答案 0 :(得分:1)

在AuthenticatedRouteGuardService

中使用此功能
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authenticationService.isAuthenticated()) {
        return true;
    }

    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
}