在AuthGuard中获取先前的路由/网址

时间:2019-08-23 16:17:06

标签: angular typescript

有时,用户可能会在不登录当前设备的情况下访问我的页面。对于这种情况,我有一个AuthGuard来检查用户是否已登录。如果没有,则将其重定向到/login页面。

现在,有时候我需要将用户登录后移到特定页面 。此外,查询参数也需要这样移动:

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

  private previousUrl: string;

  constructor(
    private _userService: UserService,
    private _router: Router,
    private _activatedRoute: ActivatedRoute,
    private _logger: NGXLogger
  ) {

    this._router.events
      .subscribe((event) => {
        this.previousUrl = null;    
        if (event instanceof NavigationCancel) {
          this.previousUrl = event.url;
        }
      });
  }

  canActivate() {

    console.log('canActivate')
    if (AuthenticationService.isLoggedIn()) {
      this._logger.debug('User is logged in.');
      return true;
    }

    let loginParams = {};

    if (this.previousUrl) {

      const url = this._activatedRoute.snapshot.url;
      const queryParams = this._activatedRoute.snapshot.queryParams;

      const paramsList = [];
      for (const k of Object.keys(queryParams)) {
        paramsList.push(`${k}=${queryParams[k]}`);
      }

      const paramsStr = paramsList.length ? `?${paramsList.join('=')}` : '';
      const enc = encodeURIComponent(`${this.previousUrl}${paramsStr}`);

      loginParams = {redirect: enc};
    }

    this._router.navigate(['/login'], {queryParams: loginParams});

    return false;
  }

  canActivateChild() {
    return this.canActivate();
  }    
}

用于路线:

{
  path: '',
  loadChildren: './module/application/application.module#ApplicationModule',
  canActivate: [AuthGuard]
},

现在,我没有找到其他方法来使用常用的URL。该解决方案的问题在于,previousUrl执行时未设置canActivate(),这意味着previousUrl在该时刻始终为undefined

AuthGuard得到控制之前,如何获得上一个URL?

我已经看过了

console.log(this._router.url);
console.log(this._activatedRoute.snapshot.url);

之前,我重定向到/login

但是_router.url已经是/login,而url快照只是一个空列表[]

1 个答案:

答案 0 :(得分:0)

将原始URL传递到登录组件:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url and return false
        this.router.navigate(['login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

参见此处:https://jasonwatmore.com/post/2016/12/08/angular-2-redirect-to-previous-url-after-login-with-auth-guard

编辑:

  

如果没有,它将被重定向到/ login页面。

这是您获取当前页面并使用防护作为参数登录组件的地方