【问题标题】:Angular 5 routing with query string带有查询字符串的Angular 5路由
【发布时间】:2018-07-11 17:48:51
【问题描述】:

我正在编写我的 Angular 5+ 应用程序并使用 AuthGuardService 我正在做的是我正在从另一个 php 应用程序重定向,该应用程序向我发送查询字符串中的表单数据

http://localhost:44200/#/users/save?first_name=John&last_name=Doe

AuthGuardService 正确重定向用户登录,如果他没有使用以下代码登录

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    if(localStorage.getItem('crmUser')){
      return true;
    }
    this.router.navigate(['/login'], { queryParams: {returnUrl: state.url},queryParamsHandling: 'merge' });
    return false;
}

但登录后如果没有查询字符串,我可以重定向返回 url,我想将用户重定向到包含所有查询字符串的同一页面。

请指导我如何处理它。

【问题讨论】:

  • queryParamsHandling : 'preserve'
  • 你可以在你的守卫中设置条件,检查url是否有你的查询字符串,如果没有,则与你想要的值匹配,然后重定向到示例页面。

标签: angular angular-routing canactivate


【解决方案1】:

我就是这样做的。在您的 AuthGuard#canActivate 添加以下内容:

@Injectable()
export class AuthGuard implements CanActivate{

  originRoute:ActivatedRouteSnapshot;

  constructor(private authentificationService: AuthChecker,
              private router: Router){}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(localStorage.getItem('crmUser')){
       return true;
    }
    this.originRoute = route;
    this.router.navigate(['/login'], { queryParams: {returnUrl: state.url},queryParamsHandling: 'merge' });
    return false;


    }
  }

  public hasOriginRoute(): boolean{
    return this.originRoute != null;

  }
}

现在登录成功后在你的 LoginComponent 中添加:

if(this.authGuard.hasOriginRoute()){
   this.router.navigate(this.authGuard.originRoute.url.map((x) => x.path));
}

【讨论】:

    猜你喜欢
    • 2012-04-01
    • 2011-01-16
    • 2014-03-05
    • 2015-11-04
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多