Angular 5 个带有查询字符串的路由

Angular 5 routing with query string

我正在编写我的 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;
}

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

请指导我如何处理。

我就是这样做的。在您的 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));
}